我有一个问题。
正如你所看到的,如果它是1,0,7 - 一切都很好,但有4和3 ......
我的代码:
def reshape_img(self):
width, height = self.img.size
new_img_list = []
for x in range(width):
white_y = 0
start_nr = False
for y in range(height):
red, green, blue = self.img.getpixel((x, y)) # Current color
if red != 255:
start_nr = True
new_y = y - white_y + 5
new_img_list.append((x, new_y, (red, green, blue)))
elif red == 255 and not start_nr:
white_y += 1
return new_img_list
def new_image(image_list):
background = (255, 255, 255, 255)
img = Image.new('RGB', (545, 20), background)
pixels = img.load()
for d in image_list:
pixels[d[0], d[1]] = d[2]
img.save('img2.png')
答案 0 :(得分:1)
不是根据该列的第一个非白色像素调整每列像素,而是查看相邻的列加上或减去某个范围(足以覆盖整个数字)并取所有这些列中的最小值。这样,数字将作为块上下移动,而不会被移动不同数量的不同列扭曲。您可以在几个过程中执行此操作,使用列表存储最小值:
def reshape_img(self):
width, height = self.img.size
y_start = [height] * width
# find the first non-white pixel of each column (checking only red channel):
for x in range(width):
for y in range(height):
red, green, blue = self.img.getpixel((x, y)) # Current color
if red != 255:
y_start[x] = y
break
new_img_list = []
for x in range(width):
# find minimum of adjacent columns +/- 5 left and right:
white_y = min(y_start[min(0,x-5):max(width-1:x+5)])
for y in range(white_y, height):
red, green, blue = self.img.getpixel((x, y)) # Current color
if red != 255:
new_y = y - white_y + 5
new_img_list.append((x, new_y, (red, green, blue)))
return new_img_list
(未经测试的代码)
此算法依赖于数字之间存在空格(如图像中所示),如果数字更改,则必须根据数字的大小和间距调整相邻列的数量。您可以通过仅占用非全白列的连续块的最小值来使其更加健壮,因此如果存在全白列,则一侧的列不会影响另一侧的列。