简体   繁体   English

在python中填充图像的“洞”,cv2无法正常工作

[英]Filling “holes” of an image in python with cv2 not working

I am trying to fill the "holes" of red blood cells in an image after performing binary threshold. 我试图在执行二进制阈值后填充图像中的红细胞“洞”。 Almost all red blood cells have a black center when inverting the binary threshold. 当反转二进制阈值时,几乎所有红细胞都具有黑色中心。 I want to remove them. 我想删除它们。

Example image: 示例图片:

示例图片


This is my code: 这是我的代码:

import cv2 
from PIL import Image
import numpy as np
from scipy import ndimage
from skimage.feature import peak_local_max
from skimage.morphology import watershed

image = cv2.imread("blood_cells.jpg")

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
darker = cv2.equalizeHist(gray)
ret,thresh = cv2.threshold(darker,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
newimg = cv2.bitwise_not(thresh)

im2, contours, hierarchy = cv2.findContours(newimg,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

for cnt in contours:
    cv2.drawContours(newimg,[cnt],0,255,-1)

And it worked. 它奏效了。 I filled the holes using findContours() and drawContours() . 我使用findContours()drawContours()来填充漏洞。

but when I try to compute the euclidean distance, for applying the watershed algorithm, I get only 52 unique segments, however there should be more. 但是当我尝试计算欧氏距离时,为了应用分水岭算法,我只得到52个独特的段,但是应该有更多。 Here is the code, if it might be helpful: 这是代码,如果它可能有用:

D = ndimage.distance_transform_edt(newimg)
localMax = peak_local_max(D, indices=False, min_distance=20, labels=thresh)
markers = ndimage.label(localMax, structure=np.ones((3, 3)))[0]
labels = watershed(-D, markers, mask=thresh)
print("[INFO] {} unique segments found".format(len(np.unique(labels)) - 1))

I tried to segment each cell, but the results were quite off. 我试图对每个细胞进行细分,但结果却很糟糕。 Only the inside of the cells that had "holes" got segmented. 只有具有“孔”的细胞内部才被分割。

First image shows my result, second shows how it should roughly look like: 第一张图显示了我的结果,第二张图显示了它的大致外观:

第一张图显示了我的结果,第二张图显示了它的粗略外观 .

I then filled the holes manually, just to see if my code for segmentation works - and it works. 然后我手动填充漏洞,只是为了看看我的分段代码是否有效 - 并且它有效。 The error should be somewhere between the part where I drew the contours, and the part where I calculated the euclidean distance.. Could anybody explain to me what could be wrong? 错误应该介于我绘制轮廓的部分和我计算欧氏距离的部分之间。任何人都可以向我解释什么可能是错的? I am clueless. 我很无能为力。

Your problem lies in the following line: 您的问题在于以下几行:

labels = watershed(-D, markers, mask=thresh)

You're passing as mask an inverted, uncorrected result from thresholding: 你作为掩码传递了一个倒置的,未校正的阈值结果:

坏面具

Giving you this bad segmentation: 给你这个糟糕的细分:

糟糕的结果

Whereas you should be passing the corrected, filled in mask: 你应该通过修正后的面具:

labels = watershed(-D, markers, mask=newimg)

好面具

Giving you the result you probably expect: 给你你可能期望的结果:

好结果

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

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