python - 是否有优化方法来查找灰度图像的左上角和右下角像素?
问题描述
我正在尝试找到一个覆盖下面(最右边)“变形”图像的轮廓:
请注意,此代码提供了 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 的回复,我能够简化我的实现:
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))
推荐阅读
- javascript - HTML Link javascript 在右键单击或 shift 单击时执行(在新窗口/选项卡中打开)
- spring-boot - 如何在 SpringBootTest 中使用 Kotlin beans dsl 初始化程序
- python - 在单个图形上叠加图
- angular - Angular 6.执行http post而不等待返回
- google-cloud-platform - Google BigQuery - 从选择语句执行动态生成的查询
- java - 类型不适用于参数(泛型问题)
- ravendb - RavenDB——更像这样——需要一个(相似性)度量;不仅仅是排名
- r - 创建某个日期后 31 天或每个 ID 的最大日期的日期变量
- angularjs - 对对象进行 ng-repeat 以创建下拉菜单
- javascript - 多个堆叠模式 bs3 中的 ESC 键错误