首页 > 解决方案 > 是否有优化方法来查找灰度图像的左上角和右下角像素?

问题描述

我正在尝试找到一个覆盖下面(最右边)“变形”图像的轮廓:

在此处输入图像描述

请注意,此代码提供了 11 或 12 个轮廓,并且没有提供可以覆盖所有白色像素的最大框:

cnts = cv2.findContours(morphed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
print('Found {} coutours'.format(len(cnts)))

所以我创建了一些函数来手动遍历图像像素:

image_height = morphed.shape[0]
image_width = morphed.shape[1]

def find_top_pixel():
    for h in range(image_height):
        for w in range(image_width):
            if morphed[h, w] > 0:
                return h

    return 0
          
def find_bottom_pixel():
    for h in range(image_height):
        for w in range(image_width):
            if morphed[-h, -w] > 0:
                return image_height - h

    return image_height


def find_left_pixel():
    for w in range(image_width):
        for h in range(image_height):       
            if morphed[h, w] > 0:
                return w

    return 0

def find_right_pixel():
    for w in range(image_width):
        for h in range(image_height):       
            if morphed[-h, -w] > 0:
                return image_width - w                

    return image_width

padding = 10
top_left = (find_left_pixel() - padding, find_top_pixel() - padding)
bottom_right = (find_right_pixel() + padding, find_bottom_pixel() + padding)

print('top_left: {}'.format(top_left))
print('bottom_right: {}'.format(bottom_right))

我能够实现我的目标:

在此处输入图像描述

有没有优化的方法?我觉得可能有一个简洁的 Python 语法,甚至是一个 opencv 属性或方法。

标签: pythonopencv

解决方案


感谢 Miki 的回复,我能够简化我的实现:

morphed_white_pixels = np.argwhere(morphed == 255)

min_y = min(morphed_white_pixels[:, 1])
max_y = max(morphed_white_pixels[:, 1])
min_x = min(morphed_white_pixels[:, 0])
max_x = max(morphed_white_pixels[:, 0])

padding = 10
top_left = (min_y - padding, min_x - padding)
bottom_right = (max_y + padding, max_x + padding)

print('top_left: {}'.format(top_left))
print('bottom_right: {}'.format(bottom_right))

推荐阅读