Python 有没有一种优化方法可以找到灰度图像的左上和右下像素?
我试图找到一个轮廓,它将覆盖下面(最右边)的“变形”图像: 请注意,此代码提供了11或12个轮廓,但没有提供可以覆盖所有白色像素的最大框:Python 有没有一种优化方法可以找到灰度图像的左上和右下像素?,python,opencv,Python,Opencv,我试图找到一个轮廓,它将覆盖下面(最右边)的“变形”图像: 请注意,此代码提供了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
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的回复,我能够简化我的实现:
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))
获取所有白色像素坐标并计算其边界框,谢谢!我现在能把它转换成13行了。