-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathremove_background.py
71 lines (57 loc) · 2.11 KB
/
remove_background.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
from PIL import Image
def remove_background(image,char_color):
# Load the image
# image = Image.open('chars/4.png')
# Create a copy of the image with an alpha channel
image = image.convert("RGBA")
data = image.getdata()
# Define the threshold for transparency
threshold = 50
new_data = []
for item in data:
if item[0] > threshold and item[1] > threshold and item[2] > threshold:
new_data.append((255, 255, 255, 0))
else:
if char_color == 'black':
new_data.append((0, 0, 0, 255))
else:
new_data.append((255, 255, 255, 255))
# new_data.append(item)
# Update the image data
image.putdata(new_data)
# Save the image with transparent background
# image.save("EIN_T.png")
return image
# def remove_background2():
# import cv2
# import numpy as np
# # Load the image
# image = cv2.imread(f"./chars/EIN.png")
# # Convert the image to grayscale
# gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# # Apply thresholding to separate the object from the background
# _, binary = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
# # Invert the binary image
# binary = cv2.bitwise_not(binary)
# # Apply bitwise AND operation to extract the object
# result = cv2.bitwise_and(image, image, mask=binary)
# # Save the result
# cv2.imwrite(f"./chars/EIN_T.png", result)
# image = cv2.imread(f"./chars/EIN_T.png")
# gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# cv2.imwrite(f"./chars/EIN_T.png", gray)
# image = Image.open(f"./chars/EIN_T.png")
# image = image.convert("RGBA")
# data = image.getdata()
# threshold = 50
# new_data = []
# for item in data:
# if item[0] > threshold and item[1] > threshold and item[2] > threshold:
# new_data.append((0, 0, 0, 255))
# else:
# new_data.append((255, 255, 255, 255))
# # Update the image data
# image.putdata(new_data)
# # Save the image with transparent background
# image.save(f"./chars/EIN_T.png")
# remove_background2()