使图像中的对象成为一行

Make objects in the image in one line

我有问题。

所以,我有这张图片,我想将所有数字放在一行中:

但我只得到了这个:

如您所见,如果是 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

(未经测试的代码)

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