首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何检测圆形腐蚀/膨胀

如何检测圆形腐蚀/膨胀
EN

Stack Overflow用户
提问于 2019-05-04 15:57:35
回答 2查看 734关注 0票数 2

我想检测一条线上的圆形侵蚀和扩张。对于扩张,我试图递归地侵蚀图像,在每次递归时,我都会检查宽高宽高比。如果比率小于4,我假设它的轮廓是圆形的,对于每个这样的轮廓,我根据矩和面积计算圆的圆心和半径。这是检测圆形扩张的函数:

代码语言:javascript
复制
def detect_circular_dilations(img, contours):
    contours_current, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    if len(contours_current) == 0:
        return get_circles_from_contours(contours)
    for c in contours_current:
        x, y, w, h = cv2.boundingRect(c)
        if w > h:
            aspect_ratio = float(w) / h
        else:
            aspect_ratio = float(h) / w
        if aspect_ratio < 4 and w < 20 and h < 20 and w > 5 and h > 5:
            contours.append(c)
    return detect_circular_dilations(cv2.erode(img, None, iterations=1), contours)

下面是我想要检测的圆形膨胀的一个例子:

我还没有解决的另一个问题是圆形腐蚀的检测。圆周侵蚀的示例如下:

在这里,我用红色矩形标记了要检测的圆形侵蚀。可能会有一些较小的圆形图案(在左侧),不应该被视为实际的圆形侵蚀。

有人知道检测这种圆形的最好方法是什么吗?对于循环扩张,我希望有任何评论/建议,以便潜在地使检测更健壮。

谢谢!

EN

回答 2

Stack Overflow用户

发布于 2019-05-05 00:01:13

我会尝试用cv2.Canny()找到这条线的两条边,然后搜索轮廓。如果您按边框的宽度对轮廓进行排序,则前两个轮廓将是您的线条边缘。之后,您可以计算一条边中的每个点到另一条边的最小距离。然后,你可以计算距离的中位数,如果一个点的距离大于或小于中位数(+-公差),那么该点就是直线的扩张或侵蚀,并将其附加到列表中。如果需要,您可以通过遍历列表来筛选噪声,如果它们不连续(在x轴上),则删除这些点。

下面是一个简单的例子:

代码语言:javascript
复制
import cv2
import numpy as np
from scipy import spatial

def detect_dilation(median, mindist, tolerance):
    count = 0
    for i in mindist:
        if i > median + tolerance:
            dilate.append((reshape_e1[count][0], reshape_e1[count][1]))
        elif i < median - tolerance:
            erode.append((reshape_e1[count][0], reshape_e1[count][1]))
        else:
            pass
        count+=1

def other_axis(dilate, cnt):
    temp = []
    for i in dilate:
        temp.append(i[0])
    for i in cnt:
        if i[0] in temp:
            dilate.append((i[0],i[1]))

img = cv2.imread('1.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,100,200)
_, contours, hierarchy = cv2.findContours(edges,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
contours.sort(key= lambda cnt :cv2.boundingRect(cnt)[3])
edge_1 = contours[0]
edge_2 = contours[1]
reshape_e1 = np.reshape(edge_1, (-1,2))
reshape_e2 =np.reshape(edge_2, (-1,2))
tree = spatial.cKDTree(reshape_e2)
mindist, minid = tree.query(reshape_e1)
median = np.median(mindist)
dilate = []
erode = []
detect_dilation(median,mindist,5)
other_axis(dilate, reshape_e2)
other_axis(erode, reshape_e2)

dilate = np.array(dilate).reshape((-1,1,2)).astype(np.int32)
erode = np.array(erode).reshape((-1,1,2)).astype(np.int32)
x,y,w,h = cv2.boundingRect(dilate)
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
x,y,w,h = cv2.boundingRect(erode)
cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2)

cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

结果:

编辑:

如果图片中有一条折线(这意味着更多的轮廓),则必须将每个轮廓视为一条单独的线。您可以通过在cv2.boundingRect()的帮助下创建一个感兴趣的区域来实现这一点。但是当我尝试新上传的图片时,这个过程并不是很健壮,因为你必须改变容差才能得到想要的结果。由于我不知道其他图像是什么样子的,你可能需要一种更好的方法来获得平均距离和容差因子。这里的任何方式都是我描述的一个示例( 15表示容差):

代码语言:javascript
复制
import cv2
import numpy as np
from scipy import spatial

def detect_dilation(median, mindist, tolerance):
    count = 0
    for i in mindist:
        if i > median + tolerance:
            dilate.append((reshape_e1[count][0], reshape_e1[count][1]))
        elif i < median - tolerance:
            erode.append((reshape_e1[count][0], reshape_e1[count][1]))
        else:
            pass
        count+=1

def other_axis(dilate, cnt):
    temp = []
    for i in dilate:
        temp.append(i[0])
    for i in cnt:
        if i[0] in temp:
            dilate.append((i[0],i[1]))

img = cv2.imread('2.jpg')
gray_original = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh_original = cv2.threshold(gray_original, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)

# Filling holes
_, contours, hierarchy = cv2.findContours(thresh_original,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
    cv2.drawContours(thresh_original,[cnt],0,255,-1)
_, contours, hierarchy = cv2.findContours(thresh_original,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)

for cnt in contours:
    x2,y,w2,h = cv2.boundingRect(cnt)
    thresh = thresh_original[0:img.shape[:2][1], x2+20:x2+w2-20] # Region of interest for every "line"
    edges = cv2.Canny(thresh,100,200)
    _, contours, hierarchy = cv2.findContours(edges,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
    contours.sort(key= lambda cnt: cv2.boundingRect(cnt)[3])
    edge_1 = contours[0]
    edge_2 = contours[1]
    reshape_e1 = np.reshape(edge_1, (-1,2))
    reshape_e2 =np.reshape(edge_2, (-1,2))
    tree = spatial.cKDTree(reshape_e2)
    mindist, minid = tree.query(reshape_e1)
    median = np.median(mindist)
    dilate = []
    erode = []
    detect_dilation(median,mindist,15)
    other_axis(dilate, reshape_e2)
    other_axis(erode, reshape_e2)
    dilate = np.array(dilate).reshape((-1,1,2)).astype(np.int32)
    erode = np.array(erode).reshape((-1,1,2)).astype(np.int32)
    x,y,w,h = cv2.boundingRect(dilate)
    if len(dilate) > 0:
        cv2.rectangle(img[0:img.shape[:2][1], x2+20:x2+w2-20],(x,y),(x+w,y+h),(255,0,0),2)
    x,y,w,h = cv2.boundingRect(erode)
    if len(erode) > 0:
        cv2.rectangle(img[0:img.shape[:2][1], x2+20:x2+w2-20],(x,y),(x+w,y+h),(0,0,255),2)

cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

结果:

票数 1
EN

Stack Overflow用户

发布于 2019-05-05 13:12:56

这类问题通常使用距离变换和中轴变换来解决。这些在某种程度上是相关的,因为中轴沿着距离变换的脊线运行。一般的想法是:

  1. 计算图像的距离变换(对于每个前景像素,返回到最近的背景像素的距离;一些库以另一种方式实现这一点,在这种情况下,您需要计算中轴(或骨架)的倒置的距离变换。
  2. 沿中轴的距离变换的值是相关值,我们忽略所有其他像素。这里我们看到了直线的局部半径,

  1. ,局部极大值是扩张的质心。使用阈值来确定其中哪些是重要的扩张,哪些不是(嘈杂的轮廓将导致许多局部最大值)。
  2. 局部最小值是侵蚀的质心。

例如,我使用下面的MATLAB代码获得了以下输出。

下面是我使用的代码。它使用MATLAB和DIPimage 3,只是作为原理的快速证明。使用您喜欢使用的任何图像处理库,这应该可以直接转换为Python。

代码语言:javascript
复制
% Read in image and remove the red markup:
img = readim('https://i.stack.imgur.com/bNOTn.jpg');
img = img{3}>100;
img = closing(img,5);

% This is the algorithm described above:
img = fillholes(img);               % Get rid of holes
radius = dt(img);                   % Distance transform
m = bskeleton(img);                 % Medial axis
radius(~m) = 0;                     % Ignore all pixels outside the medial axis
detection = dilation(radius,25)==radius & radius>25; % Local maxima with radius > 25
pos = findcoord(detection);         % Coordinates of detections
radius = double(radius(detection)); % Radii of detections

% This is just to make the markup:
detection = newim(img,'bin');
for ii=1:numel(radius)
   detection = drawshape(detection,2*radius(ii),pos(ii,:),'disk');
end
overlay(img,detection)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55980638

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档