-
Notifications
You must be signed in to change notification settings - Fork 0
/
helper.py
76 lines (69 loc) · 2.43 KB
/
helper.py
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
from PIL import Image
def force_pixels(image_path, colors_to_compare) -> Image:
img = Image.open(image_path)
img = img.convert('RGB')
width, height = img.size
for y in range(height):
for x in range(width):
col = img.getpixel((x, y))
closest_color = None
min_distance = float('inf')
for target_color in colors_to_compare:
distance = sum(abs(c1 - c2) for c1, c2 in zip(col, target_color))
if distance < min_distance:
min_distance = distance
closest_color = target_color
img.putpixel((x, y), closest_color)
return img
def delete_bg(image_path) -> Image:
img = Image.open(image_path)
img = img.convert('RGBA')
width, height = img.size
for y in range(height):
for x in range(width):
r,g,b,a = img.getpixel((x, y))
a=255-int((r+g+b)/3)
newcol = (r,g,b,a)
img.putpixel((x,y),newcol)
return img
def upscale_image(image_path, scale) -> Image:
img = Image.open(image_path)
img = img.convert('RGB')
width, height = img.size
rgb_array = []
for y in range(height):
row = []
for x in range(width):
r, g, b = img.getpixel((x, y))
for _ in range(scale):
row.append((r, g, b))
for _ in range(scale):
rgb_array.append(row)
height = len(rgb_array)
width = len(rgb_array[0])
img = Image.new('RGB', (width, height))
for y in range(height):
for x in range(width):
img.putpixel((x, y), rgb_array[y][x])
return img
def main() -> None:
while True:
image_path = "img\\"+input("image src: ")
image_out_path = "img\\"+input("image out: ")
image:Image = None
a = input("mode: ")
if a == "setColors" or a == "sc":
rgb_colors = [(76,76,76),(33,33,33),(127,127,127),(184,121,76)]
#rgb_colors = [(0,0,0),(255,255,255),(255,0,0),(255,255,0),(0,0,255)]
image = force_pixels(image_path, rgb_colors)
if a == "upscale" or a == "us":
scale = int(input("x:"))
image = upscale_image(image_path, scale)
if a == "removeBg" or a == "bg":
image = delete_bg(image_path)
if a == "q" or a == "quit":
break
image.show()
image.save(f"{image_out_path}.png")
if __name__ == "__main__":
main()