python - 将图像中的对象排成一行

标签 python python-imaging-library

我有一个问题。

所以,我有这张图片,我想将所有数字放在一行上: enter image description here

但我只得到这个: enter image description here

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

相关文章:

python - 在 scikits learn 中使用 cross_val_score 时保留拟合参数

python - Sklearn kNN 使用用户定义的指标

python - 不支持的操作 : fileno - How to fix this Python dependency mess?

python - 为什么此代码使 Tkinter 窗口不断自动调整大小/增长?

python - 在 mac Mountain Lion 上安装 libjpeg for pil 和 Google app engine

python - 确定 numpy 数组的 2 个(垂直或水平)相邻元素是否具有相同值的最快方法

python - 值错误: unsupported format character '{' (0x7b) at index

python - 如何有效地 blit 72 图像

python - 带有 PyDev 的 PIL 模块

python - 将Numpy图像数组转换为1px高版本