我有一个问题。
如您所见,如果是 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')
最佳答案
不要根据该列的第一个非白色像素来调整每列像素,而是查看相邻的列加或减一定范围(足以覆盖整个数字)并取所有列中的最小值。这样,数字将作为一个 block 上下移动,并且不会因不同列移动不同量而扭曲。您可以使用列表来存储最小值,分几次完成:
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
(未经测试的代码)
此算法依赖于数字之间的空格(如图像中所示),如果数字发生变化,您必须根据数字的大小和间距调整相邻列的数量。您可以通过仅取非全白列的连续 block 的最小值来使其更加健壮,因此,如果存在全白列,则一侧的列不会影响另一侧的列。
关于python - 将图像中的对象排成一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46879270/