added color maps

This commit is contained in:
Askill 2022-06-07 14:50:40 +02:00
parent e9a00b3027
commit b642014c8b
3 changed files with 77 additions and 22 deletions

View File

@ -10,22 +10,43 @@ export default {
components: { components: {
HelloWorld HelloWorld
}, },
created(){ mounted(){
var wsConnection = new WebSocket('ws://localhost:8080/get'); var wsConnection = new WebSocket('ws://localhost:8080/get');
wsConnection.onopen = (e) => {
console.log(`wsConnection open to 127.0.0.1:8080`, e);
};
wsConnection.onerror = (e) => {
console.error(`wsConnection error `, e);
};
wsConnection.onmessage = (e) => {
var canvas = document.getElementById("main_canvas"); var canvas = document.getElementById("main_canvas");
var ctx = canvas.getContext("2d"); var ctx = canvas.getContext("2d");
let data = JSON.parse(e.data)
ctx.fillStyle = "rgba("+data["color"]+","+data["color"]+","+data["color"]+","+(255)+")"; var colorpalettte = [
ctx.fillRect(data["y"], data["x"], 1, 1); "#FFFFFF",
}; "#E4E4E4",
"#888888",
"#222222",
"#FFA7D1",
"#E50000",
"#E59500",
"#A06A42",
"#E5D900",
"#94E044",
"#02BE01",
"#00D3DD",
"#0083C7",
"#0000EA",
"#CF6EE4",
"#820080"
]
wsConnection.onopen = (e) => {
console.log(`wsConnection open`, e);
};
wsConnection.onerror = (e) => {
console.error(`wsConnection error `, e);
};
wsConnection.onmessage = (e) => {
let data = JSON.parse(e.data)
ctx.fillStyle = colorpalettte[parseInt(data["color"])];
ctx.fillRect(data["y"], data["x"], 1, 1);
};
} }
} }
</script> </script>
@ -38,5 +59,9 @@ wsConnection.onmessage = (e) => {
text-align: center; text-align: center;
color: #2c3e50; color: #2c3e50;
margin-top: 60px; margin-top: 60px;
}
body{
background-color: grey;
} }
</style> </style>

View File

@ -53,7 +53,7 @@ func (img *image) SetPixel(message Message) int {
fmt.Printf("User %d tried accessing out of bounds \n", message.UserID) fmt.Printf("User %d tried accessing out of bounds \n", message.UserID)
return 1 return 1
} }
if message.Color > 255 || message.Color < 0 { if message.Color > 15 || message.Color < 0 {
fmt.Printf("User %d tried setting non existent color %d \n", message.UserID, message.Color) fmt.Printf("User %d tried setting non existent color %d \n", message.UserID, message.Color)
return 1 return 1
} }

View File

@ -3,7 +3,7 @@
import asyncio import asyncio
from dataclasses import dataclass from dataclasses import dataclass
import datetime import datetime
from PIL import Image
import json import json
from multiprocessing import Pool from multiprocessing import Pool
import random import random
@ -25,6 +25,39 @@ class pixel:
timestamp: int timestamp: int
userid: int userid: int
def hex_to_rgb(h):
return tuple(int(h[i:i+2], 16) for i in (0, 2, 4))
hex_colors = [
"#FFFFFF",
"#E4E4E4",
"#888888",
"#222222",
"#FFA7D1",
"#E50000",
"#E59500",
"#A06A42",
"#E5D900",
"#94E044",
"#02BE01",
"#00D3DD",
"#0083C7",
"#0000EA",
"#CF6EE4",
"#820080"
]
rgb_colors = [hex_to_rgb(h[1:]) for h in hex_colors]
def eucleadian_distance(rgb1, rgb2):
if len(rgb1) != len(rgb2):
raise ValueError
sum_part = np.sum([(rgb1[i]-rgb2[i])**2 for i in range(len(rgb1))])
# return np.sqrt(sum_part) # technically correct, but we only care about rank not exact distance and sqrt is expensive
return sum_part
def closest_match(rgb, color_map):
return min(range(len(rgb_colors)), key=lambda i: eucleadian_distance(rgb, color_map[i]))
async def sender(img): async def sender(img):
async with websockets.connect("ws://localhost:8080/set") as websocket: async with websockets.connect("ws://localhost:8080/set") as websocket:
while True: while True:
@ -33,7 +66,7 @@ async def sender(img):
message = pixel( message = pixel(
x=rx, x=rx,
y=ry, y=ry,
color=int(sum(img[rx][ry])/3), color= closest_match(img[rx][ry], rgb_colors),
timestamp=int(time.time()), timestamp=int(time.time()),
userid=1, userid=1,
) )
@ -46,17 +79,12 @@ async def sender(img):
async def client(): async def client():
image = np.zeros(shape=[1000, 1000, 3], dtype=np.uint8) image = np.zeros(shape=[1000, 1000, 3], dtype=np.uint8)
colors = []
for name, hex in matplotlib.colors.cnames.items():
colors.append(matplotlib.colors.to_rgb(hex))
async with websockets.connect("ws://localhost:8080/get") as websocket: async with websockets.connect("ws://localhost:8080/get") as websocket:
i= 0 i= 0
while True: while True:
i+=1 i+=1
x = pixel(**json.loads(await websocket.recv())) x = pixel(**json.loads(await websocket.recv()))
#image[x.x][x.y] = ([y*255 for y in colors[x.color]]) image[x.x][x.y] = rgb_colors[x.color]
image[x.x][x.y] = ((x.color, x.color, x.color))
#if i% 5000 == 0: #if i% 5000 == 0:
# cv2.imshow("changes x", image) # cv2.imshow("changes x", image)
# cv2.waitKey(10) & 0XFF # cv2.waitKey(10) & 0XFF
@ -64,7 +92,9 @@ async def client():
#print(i, x) #print(i, x)
async def main(): async def main():
img=mpimg.imread('./1.jpg') img= Image.open('./2.jpg')
img= img.resize((1000, 1000), Image.ANTIALIAS)
img = np.array(img)
coros = [sender(img) for _ in range(100)] coros = [sender(img) for _ in range(100)]
coros.append(client()) coros.append(client())
returns = await asyncio.gather(*coros) returns = await asyncio.gather(*coros)