使用OpenCV提取最大的斑块

3
我有一张二进制图像,将人类描绘为白色斑点,背景为黑色。我想使用opencv从大图像中“裁剪”最大的(或3个最大的)斑点。 如何操作呢?

1
你有尝试过什么吗?或者你有任何可以展示给我们的代码吗? - Sharad Khanna
尝试这个:https://stackoverflow.com/questions/15693900/how-to-determine-a-region-of-interest-and-then-crop-an-image-using-opencv - Emanuel Huber
1个回答

2

我不确定你是否已经找到了答案,但是根据我理解的需求,以下是基本代码结构。您可以根据需要进行修改。

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 的感兴趣区域。
希望这能帮到您!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接