简体   繁体   English

如何从二值图像中找到最大的白色像素区域

[英]How to find the largest white pixel region from a binary image

I have been working on a binary image on opencv python.我一直在研究 opencv python 上的二进制图像。 I need to get the largest region.我需要获得最大的区域。 I have used following code, but I am not getting desired output.我使用了以下代码,但没有获得所需的输出。

edged = cv2.Canny(im_bw, 35, 125)
(cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
c = max(cnts, key = cv2.contourArea)

You don't need to use the canny output to do this.您不需要使用精明的输出来执行此操作。 Just do findContours on im_bw directly and you should get the desired results.直接在im_bw上做findContours ,你应该得到想要的结果。 If still not what you want, try to use different threshold values (given that your original image isn't BW itself)如果仍然不是您想要的,请尝试使用不同的阈值(假设您的原始图像本身不是 BW)

(_, im_bw) = threshold(frame, 100, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
(cnts, _) = cv2.findContours(im_bw.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
c = max(cnts, key = cv2.contourArea)

You really didn't explain what are you looking for,"largest region"?你真的没有解释你在找什么,“最大区域”? The code you posted will give you the largest contour found but you need to understand what is an OpenCV contour here .您发布的代码将为您提供找到的最大轮廓,但您需要了解此处的 OpenCV 轮廓是什么。 Now depending of your image you can have a lot of noise and that makes OpenCV gives you not the "region" you are expecting, so you need to reduce the noise.现在取决于你的图像,你可能会有很多噪音,这使得 OpenCV 给你不是你期望的“区域”,所以你需要减少噪音。 Before apply the Canny or the threshold you can apply BLUR to the image, EROTION and/or DILATION .在应用 Canny 或阈值之前,您可以将BLUR应用于图像、 EROTION 和/或 DILATION

The algorithm should be like this:算法应该是这样的:

  • Get the frame / image获取框架/图像
  • Grayscale it灰度它
  • Apply Blur / Erode / Dilate to reduce noise应用模糊/侵蚀/扩张来减少噪音
  • Apply Canny or threshold应用 Canny 或阈值
  • Find contours查找轮廓
  • Get the largest获得最大的
  • Do what you need做你需要的

Here you'll find good documentation in Python. 在这里你会找到很好的 Python 文档。

I am using the scikit-image package of python which measures the area of the islands and chooses the largest area as follows -我正在使用 python 的scikit-image包,它测量岛屿的面积并选择最大的面积如下 -

import skimage
from skimage import measure

labels_mask = measure.label(input_mask)                       
regions = measure.regionprops(labels_mask)
regions.sort(key=lambda x: x.area, reverse=True)
if len(regions) > 1:
    for rg in regions[1:]:
        labels_mask[rg.coords[:,0], rg.coords[:,1]] = 0
labels_mask[labels_mask!=0] = 1
mask = labels_mask

Input image -输入图像 -

在此处输入图片说明

Output image -输出图像 -

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM