我试图找到一个轮廓,它将覆盖下面(最右边)的“变形”图像:
请注意,此代码提供了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属性或方法
感谢Miki的回复,我能够简化我的实现:
相关问题 更多 >
编程相关推荐