-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPixel
More file actions
85 lines (69 loc) · 2.83 KB
/
Pixel
File metadata and controls
85 lines (69 loc) · 2.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import pygame as pg
import cv2
import numpy as np
class Converter:
def _init_(self, path="Monalisa_2.jpg", pixel_size=3, color_lvl=8):
pg.init()
self.path = path
self.PIXEL_SIZE = pixel_size
self.COLOR_LVL = color_lvl
self.cv2_image = cv2.imread(self.path)
self.image = self.get_image()
self.RES = self.WIDTH, self.HEIGHT = self.image.shape[0], self.image.shape[1]
self.surface = pg.display.set_mode(self.RES)
self.clock = pg.time.Clock()
self.PALETTE, self.COLOR_COEFF = self.create_palette()
def draw_converted_image(self):
color_indices = self.image // self.COLOR_COEFF
pixels = pg.surfarray.pixels3d(self.surface)
for x in range(0, self.WIDTH, self.PIXEL_SIZE):
for y in range(0, self.HEIGHT, self.PIXEL_SIZE):
color_key = tuple(color_indices[x, y])
if sum(color_key):
color = self.PALETTE[color_key]
pixels[x:x + self.PIXEL_SIZE, y:y + self.PIXEL_SIZE] = color
def create_palette(self):
colors, color_coeff = np.linspace(0, 255, num=self.COLOR_LVL, dtype=int, retstep=True)
color_palette = [np.array([r, g, b]) for r in colors for g in colors for b in colors]
palette = {}
color_coeff = int(color_coeff)
for color in color_palette:
color_key = tuple(color // color_coeff)
palette[color_key] = tuple(color)
return palette, color_coeff
def get_image(self):
transposed_image = cv2.transpose(self.cv2_image)
image = cv2.cvtColor(transposed_image, cv2.COLOR_BGR2RGB)
return image
def draw_cv2_image(self):
resized_cv2_image = cv2.resize(self.cv2_image, (640, 360), interpolation=cv2.INTER_AREA)
cv2.imshow("img", resized_cv2_image)
def draw(self):
self.surface.fill('black')
self.draw_converted_image()
self.draw_cv2_image()
def save_image(self):
self.draw_converted_image()
# Get pixel data from the surface
pixel_array = pg.surfarray.array3d(self.surface)
# Convert RGB to BGR for cv2
bgr_array = np.flip(pixel_array, axis=2)
# Save the image using cv2
cv2.imwrite('hell.png', cv2.cvtColor(bgr_array, cv2.COLOR_RGB2BGR))
def run(self):
while True:
for i in pg.event.get():
if i.type == pg.QUIT:
pg.quit()
quit()
elif i.type == pg.KEYDOWN:
if i.key == pg.K_s:
self.save_image()
self.draw()
pg.display.set_caption(str(self.clock.get_fps()))
pg.display.flip()
self.clock.tick()
cv2.imshow('img', self.cv2_image)
if _name_ == "_main_":
app = Converter()
app.run()