python - 用opencv提取最大的blob

标签 python c++ opencv blob

我有一张二值图像,将人类描绘成白色 Blob ,将背景描绘成黑色。我想使用 opencv 从大图像中“裁剪”最大(或 3 个最大)的 Blob 。

人们会怎么做呢?

最佳答案

我不确定您是否找到了答案,但这里是基于我理解的您的要求的代码的基本结构。您可以根据需要修改它。

import numpy as np
import cv2

# load the image
image = cv2.imread("path_to_your_image.png") # if this not a binary image, you can threshold it
output = image.copy()

im2,contours,hierarchy = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

if len(contours) != 0:
    # the contours are drawn here
    cv2.drawContours(output, contours, -1, 255, 3)

    #find the biggest area of the contour
    c = max(contours, key = cv2.contourArea)

    x,y,w,h = cv2.boundingRect(c)
    # draw the 'human' contour (in green)
    cv2.rectangle(output,(x,y),(x+w,y+h),(0,255,0),2)

# show the image
cv2.imshow("Result", output)

cv2.waitKey(0)

注意:x、y、x+w 和 y+h 为您提供框的范围,因此使用这些值您可以获得最大 Blob 的感兴趣区域。

希望对您有所帮助!

关于python - 用opencv提取最大的blob,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49805514/

相关文章:

python - 条件语句上的Python IndexError

python - Django Rest Framework 在序列化程序中返回 403

Python 和 Matplot : how to set auto-offset?

c++ - 返回引用与类型

python - 如何通过 python 在 openCV 3 中使用 STAR 检测器?

c++ - 如何在 x86_64 上交叉编译 Raspberry Pi 项目? (缺少 *.so 由于路径无效)

python - 查找标题包含文本的 anchor

c++ - if else 比 if + default 快吗?

c++ - 如何尽可能均匀地分类(或分配)结构?

python-2.7 - 为什么OpenCV在视频处理过程中会检索此错误?错误:(-215)scn == 3 || scn == 4在函数cv::cvtColor中