-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprepare.py
187 lines (152 loc) · 6.69 KB
/
prepare.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
from PIL import Image, ImageChops
import os
import cv2
import numpy as np
# 글자 가장자리 여백을 자르는 함수
def crop(image):
white = Image.new(image.mode, image.size, image.getpixel((0, 0)))
diff = ImageChops.difference(image, white)
diff = ImageChops.add(diff, diff, 2.0, -35)
bbox = diff.getbbox()
if bbox:
return image.crop(bbox)
else: # 이미지가 너무 작을 경우 bbox값이 없을 수도 있음
print("crop fail")
return
# def crop_to_black(folder_path):
# # 지정한 폴더 내의 모든 파일에 대해
# for filename in os.listdir(folder_path):
# # 이미지 파일만 처리
# if filename.endswith(".PNG"):
# # 이미지 파일 경로
# image_path = os.path.join(folder_path, filename)
# # OpenCV를 이용하여 이미지 읽기
# image_cv = cv2.imread(image_path)
# # 그레이스케일 이미지로 변환
# gray_image = cv2.cvtColor(image_cv, cv2.COLOR_BGR2GRAY)
# # 이진화 처리
# _, binary_image = cv2.threshold(gray_image, 128, 255, cv2.THRESH_BINARY)
#
# # 이미지 저장 (덮어쓰기)
# cv2.imwrite(image_path, binary_image)
def crop_to_black(folder_path):
# 지정한 폴더 내의 모든 파일에 대해
for filename in os.listdir(folder_path):
# 이미지 파일만 처리
if filename.endswith(".PNG"):
# 이미지 파일 경로
image_path = os.path.join(folder_path, filename)
# OpenCV를 이용하여 이미지 읽기 (알파 채널 포함)
image_cv = cv2.imread(image_path, cv2.IMREAD_UNCHANGED)
# 그레이스케일 이미지로 변환
gray_image = cv2.cvtColor(image_cv, cv2.COLOR_BGRA2GRAY)
# 이진화 처리
_, binary_image = cv2.threshold(gray_image, 128, 255, cv2.THRESH_BINARY)
# 알파 채널 추가
bgra = cv2.cvtColor(binary_image, cv2.COLOR_GRAY2BGRA)
bgra[:, :, 3] = image_cv[:, :, 3]
# 이미지 저장 (덮어쓰기)
cv2.imwrite(image_path, bgra)
# 흰 배경을 투명화시키는 함수
def transparent(image):
image = image.convert("RGBA")
data = image.getdata()
new_data = []
cut_off = 150
for datum in data:
if datum[0] >= cut_off and datum[1] >= cut_off and datum[2] >= cut_off:
new_data.append((255, 255, 255, 0))
else:
new_data.append(datum)
image.putdata(new_data)
return image
def rescale_image_width(image, rescale_width, rescale_height):
width, height = image.size
new_width = int(rescale_width)
new_height = int(rescale_height)
return image.resize((new_width, new_height), Image.LANCZOS)
def rescale_image_ratio(image, rescale_width=None, rescale_height=None):
width, height = image.size
if rescale_width is not None:
# Calculate new height preserving aspect ratio
aspect_ratio = width / height
new_width = int(rescale_width)
new_height = int(new_width / aspect_ratio)
elif rescale_height is not None:
# Calculate new width preserving aspect ratio
aspect_ratio = height / width
new_height = int(rescale_height)
new_width = int(new_height / aspect_ratio)
else:
raise ValueError("Either 'rescale_width' or 'rescale_height' must be provided.")
return image.resize((new_width, new_height), Image.LANCZOS)
def run():
for i in range(1, 41):
# 이미지 파일 읽기
image = Image.open("./images/" + str(i) + ".PNG")
# 가장자리 여백 자르기
image = crop(image)
# 흰 배경 투명화
# image = transparent(image)
rescale_image_width(image, 20, 20)
image.save("./crops/" + str(i) + ".PNG")
# crop_to_black("./crops/")
def transletters():
print('resizing 시작')
files_path = os.path.abspath("./combinations")
image_list = [os.path.join(files_path, f) for f in os.listdir(files_path) if f.lower().endswith('.png')]
letters_dir = "./letters"
if not os.path.exists(letters_dir):
os.makedirs(letters_dir)
for img_path in image_list:
image = Image.open(img_path)
cropped_image = crop(image)
result = transparent(cropped_image)
file_name = os.path.basename(img_path)
result_path = os.path.join("./letters", file_name)
result.save(result_path, "PNG")
files_path2 = os.path.abspath("./letters")
image_list2 = [os.path.join(files_path2, f) for f in os.listdir(files_path2) if f.endswith('.PNG')]
image_list2 = sorted(image_list2)
letters_dir = "./letters2"
if not os.path.exists(letters_dir):
os.makedirs(letters_dir)
# print(image_list2)
for img_path2 in image_list2:
background_file = './images/background.png'
background = Image.open(background_file)
image = Image.open(img_path2)
# Get the size of both images
bg_width, bg_height = background.size
img_width, img_height = image.size
# Calculate new size based on the longer dimension of the image.
if img_width > img_height:
new_width = bg_width - 10 # leave a small margin
scale_factor = new_width / img_width
new_height = int(scale_factor * img_height)
else:
new_height = bg_height - 10
scale_factor = new_height / img_height
new_width = int(scale_factor * img_width)
# if (new_width > bg_width): # Check whether it exceeds other dimension of background.
# new_width = bg_width - 10
# scale_factor = new_width / img_width
# new_height = int(scale_factor * img_height)
# Resize and center align the image.
resized_image = image.resize((new_width, new_height), Image.LANCZOS)
pos_x = (bg_width - new_width) // 2
pos_y = (bg_height - new_height) // 2
pos_centered = (pos_x, pos_y)
background.paste(resized_image, pos_centered, resized_image)
# background.paste(image, img_pos)
background_np = np.array(background)
background_cv = cv2.cvtColor(background_np, cv2.COLOR_RGB2BGR)
gray_image = cv2.cvtColor(background_cv, cv2.COLOR_BGR2GRAY)
_, binary_image = cv2.threshold(gray_image, 128, 255, cv2.THRESH_BINARY)
# Normalize image
normalized_image = cv2.equalizeHist(binary_image)
file_name = os.path.basename(img_path2)
result_path = os.path.join('./letters2', file_name)
# normalized_image.save(result_path, 'PNG')
cv2.imwrite(result_path, normalized_image)
print('resizing 끝')