Python 使图像中的对象成一行

Python 使图像中的对象成一行,python,python-imaging-library,pillow,Python,Python Imaging Library,Pillow,我有个问题 我有这张图,我想把所有的数字放在一行上: 但我只得到了这个: 正如你所看到的,如果它是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(h

我有个问题

我有这张图,我想把所有的数字放在一行上:

但我只得到了这个:

正如你所看到的,如果它是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')

不要只根据该列的第一个非白色像素调整每列像素,而是查看相邻的列加上或减去某个范围(足以覆盖整个数字),并取所有列的最小值。这样,数字将作为一个块上下移动,而不会被移动不同数量的不同列所扭曲。您可以通过使用列表来存储最小值,在几次过程中完成此操作:

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
(未测试代码)


此算法依赖于数字之间存在空格(如图像中的空格),如果数字发生变化,则必须根据数字的大小和间距调整相邻列的数量。通过只取非全白色列的连续块的最小值,可以使其更加健壮,因此,如果存在全白色列,则一侧的列不会影响另一侧的列。

您能否仅使用
4
创建一个示例?请参见如何创建一个。