python - 在图像中找到最少数量的矩形

标签 python numpy image-processing scipy rectangles

我有矩形随机放置的二进制图像,我想获得这些矩形的位置和大小。
如果可能,我想要 所需的最少矩形数量完全重新创建图像 .

左边是我的原始图片,右边是我申请后得到的图片scipys.find_objects()(就像对 this question 的建议)。

rectangles
rectangles

import scipy

# image = scipy.ndimage.zoom(image, 9, order=0)
labels, n = scipy.ndimage.measurements.label(image, np.ones((3, 3)))
bboxes = scipy.ndimage.measurements.find_objects(labels)

img_new = np.zeros_like(image)
for bb in bboxes:
    img_new[bb[0], bb[1]] = 1

如果矩形相距很远,这可以正常工作,但是如果它们重叠并构建更复杂的结构,则该算法只会给我最大的边界框(对图像进行上采样没有区别)。我感觉应该已经存在一个 scipyopencv这样做的方法。
我很高兴知道是否有人对如何解决这个问题有想法,或者甚至更了解现有的解决方案。

As result I want a list of rectangles (ie. lower-left-corner : upper-righ-corner) in the image. The condition is that when I redraw those filled rectangles I want to get exactly the same image as before. If possible the number of rectangles should be minimal.



这是生成示例图像的代码(以及更复杂的示例 originalscipy )
import numpy as np 

def random_rectangle_image(grid_size, n_obstacles, rectangle_limits):
    n_dim = 2
    rect_pos = np.random.randint(low=0, high=grid_size-rectangle_limits[0]+1,
                                 size=(n_obstacles, n_dim))
    rect_size = np.random.randint(low=rectangle_limits[0],
                                  high=rectangle_limits[1]+1,
                                  size=(n_obstacles, n_dim))

    # Crop rectangle size if it goes over the boundaries of the world
    diff = rect_pos + rect_size
    ex = np.where(diff > grid_size, True, False)
    rect_size[ex] -= (diff - grid_size)[ex].astype(int)

    img = np.zeros((grid_size,)*n_dim, dtype=bool)
    for i in range(n_obstacles):
        p_i = np.array(rect_pos[i])
        ps_i = p_i + np.array(rect_size[i])
        img[tuple(map(slice, p_i, ps_i))] = True
    return img

img = random_rectangle_image(grid_size=64, n_obstacles=30, 
                             rectangle_limits=[4, 10])

最佳答案

这里有一些东西可以让你开始:一个简单的算法,它遍历你的图像并创建尽可能大的矩形。就像现在一样,它只标记矩形,但不报告坐标或计数。这是为了单独可视化算法。

除了 PIL,它不需要任何外部库,在保存为 PNG 时加载和访问左侧图像。我假设可以忽略周围 15 个像素的边框。

from PIL import Image

def fill_rect (pixels,xp,yp,w,h):
    for y in range(h):
        for x in range(w):
            pixels[xp+x,yp+y] = (255,0,0,255)
    for y in range(h):
        pixels[xp,yp+y] = (255,192,0,255)
        pixels[xp+w-1,yp+y] = (255,192,0,255)
    for x in range(w):
        pixels[xp+x,yp] = (255,192,0,255)
        pixels[xp+x,yp+h-1] = (255,192,0,255)

def find_rect (pixels,x,y,maxx,maxy):
    # assume we're at the top left
    # get max horizontal span
    width = 0
    height = 1
    while x+width < maxx and pixels[x+width,y] == (0,0,0,255):
        width += 1
    # now walk down, adjusting max width
    while y+height < maxy:
        for w in range(x,x+width,1):
            if pixels[x,y+height] != (0,0,0,255):
                break
        if pixels[x,y+height] != (0,0,0,255):
            break
        height += 1
    # fill rectangle
    fill_rect (pixels,x,y,width,height)

image = Image.open('A.png')
pixels = image.load()
width, height = image.size

print (width,height)

for y in range(16,height-15,1):
    for x in range(16,width-15,1):
        if pixels[x,y] == (0,0,0,255):
            find_rect (pixels,x,y,width,height)

image.show()

从输出

found rectangles are marked in orange

您可以观察到检测算法可以改进,例如,“明显”的左上角两个矩形被分成 3 个。类似地,中心的较大结构也包含一个超出绝对需要的矩形。

可能的改进是调整 find_rect例程来定位最合适的¹,或存储坐标并使用数学(超出我的知识)来查找可以连接的矩形。

¹ 对此的进一步想法。当前,所有找到的矩形都会立即填充为“找到”的颜色。您可以尝试检测明显的多个矩形,然后在标记第一个矩形之后,其他要检查的矩形可能是黑色或红色。顺便说一句,我会说您需要尝试不同的扫描顺序(从上到下或反向、从左到右或反向)才能实际找到任意组合中最少需要的矩形数量。

关于python - 在图像中找到最少数量的矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60208143/

相关文章:

python - 如何将 float 的 2D std vector 写入 HDF5 文件,然后在 python 中读取它

python - 检测轻微噪声数据的逐渐增加然后减少

python - 如何使彩色图像的光线均匀?

image-processing - 获取 ITK 中的区域最小坐标

python - 如何在Python中使用SURF?

python - 使用 urllib2 从 FlightRadar24 获取数据时出现问题

python - Python 中区分大小写的字符串比较

python - 处理数组中的行组合并输出多个数组

用于出版质量图的 Python Pylab pcolor 选项

python - 加速 numpy 小函数