OpenCV检测图像上的斑点

Sia*_*hei 18 opencv objective-c opencv3.0 opencv3.1

我需要在图像上找到(并绘制rect)/获取最大和最小半径 blob.(以下样本)

问题是为图像找到正确的过滤器,允许CannyThreshold转换以突出显示blob.然后我将用来findContours找到矩形.

我试过了:

  • Threshold - 不同级别

  • blur->erode->erode->grayscale->canny

  • 用各种"线条" 改变图像色调

等.更好的结果是检测斑块(20-30%).并且此信息不允许在blob周围绘制rect.此外,感谢阴影,检测到与blob点无关,因此也阻止了检测区域.

据我所知,我需要找到具有强烈对比度的计数器(不像阴影那样平滑).有没有办法用openCV做到这一点?

更新

案例分开:图像1,图像2,图像3,图像4,图像5,图像6,图像7,图像8,图像9,图像10,图像11,图像12

还有一个更新

我相信斑点在边缘有对比区域.所以,我试图让边缘更强:我已经创建了2 gray scale Mat: A and B,申请Gaussian blur了第二个 - B (为了减少噪点),然后我做了一些计算:绕过每个像素并找到Xi,Yi' 之间的最大差异'来自'B'的'和附近的点:

在此输入图像描述

并适用max差异Xi,Yi.所以我得到这样的smth:

在此输入图像描述

我是在正确的方式吗?顺便说一句,我可以通过OpenCV方法达到smth吗?

更新 图像去噪有助于减少噪音,Sobel- 突出轮廓,然后threshold+findContourscustome convexHull获得与我正在寻找的相似但不适合某些斑点.

m3h*_*h0w 6

由于输入图像之间存在很大差异,因此算法应该能够适应这种情况.由于Canny基于检测高频,我的算法将图像的清晰度视为用于预处理自适应的参数.我不想花费一周时间来确定所有数据的功能,因此我应用了基于2个图像的简单线性函数,然后使用第三个图像进行了测试.这是我的结果:

第一个结果

第二个结果

第三个结果

请记住,这是一种非常基本的方法,只是证明了一点.它需要实验,测试和精炼.我们的想法是使用Sobel并对所有获得的像素求和.除以图像的大小,它应该给你一个高频率的基本估计.图像的响应.现在,通过实验,我发现CLAHE过滤器的clipLimit值在2个测试用例中工作,并找到了连接高频率的线性函数.用CLAHE滤波器响应输入,产生良好的结果.

sobel = get_sobel(img)
clip_limit = (-2.556) * np.sum(sobel)/(img.shape[0] * img.shape[1]) + 26.557
Run Code Online (Sandbox Code Playgroud)

这是适应性部分.现在为轮廓.我花了一段时间才弄清楚滤除噪音的正确方法.我选择了一个简单的技巧:使用两次轮廓查找.首先,我用它来过滤掉不必要的,嘈杂的轮廓.然后我继续使用一些形态魔法来为正在检测的对象找到正确的blob(代码中的更多细节).最后一步是根据计算的平均值过滤边界矩形,因为在所有样本上,斑点的大小相对相似.

import cv2
import numpy as np


def unsharp_mask(img, blur_size = (5,5), imgWeight = 1.5, gaussianWeight = -0.5):
    gaussian = cv2.GaussianBlur(img, (5,5), 0)
    return cv2.addWeighted(img, imgWeight, gaussian, gaussianWeight, 0)


def smoother_edges(img, first_blur_size, second_blur_size = (5,5), imgWeight = 1.5, gaussianWeight = -0.5):
    img = cv2.GaussianBlur(img, first_blur_size, 0)
    return unsharp_mask(img, second_blur_size, imgWeight, gaussianWeight)


def close_image(img, size = (5,5)):
    kernel = np.ones(size, np.uint8)
    return cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)


def open_image(img, size = (5,5)):
    kernel = np.ones(size, np.uint8)
    return cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)


def shrink_rect(rect, scale = 0.8):
    center, (width, height), angle = rect
    width = width * scale
    height = height * scale
    rect = center, (width, height), angle
    return rect


def clahe(img, clip_limit = 2.0):
    clahe = cv2.createCLAHE(clipLimit=clip_limit, tileGridSize=(5,5))
    return clahe.apply(img)


def get_sobel(img, size = -1):
    sobelx64f = cv2.Sobel(img,cv2.CV_64F,2,0,size)
    abs_sobel64f = np.absolute(sobelx64f)
    return np.uint8(abs_sobel64f)


img = cv2.imread("blobs4.jpg")
# save color copy for visualizing
imgc = img.copy()
# resize image to make the analytics easier (a form of filtering)
resize_times = 5
img = cv2.resize(img, None, img, fx = 1 / resize_times, fy = 1 / resize_times)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# use sobel operator to evaluate high frequencies
sobel = get_sobel(img)
# experimentally calculated function - needs refining
clip_limit = (-2.556) * np.sum(sobel)/(img.shape[0] * img.shape[1]) + 26.557

# don't apply clahe if there is enough high freq to find blobs
if(clip_limit < 1.0):
    clip_limit = 0.1
# limit clahe if there's not enough details - needs more tests
if(clip_limit > 8.0):
    clip_limit = 8

# apply clahe and unsharp mask to improve high frequencies as much as possible
img = clahe(img, clip_limit)
img = unsharp_mask(img)

# filter the image to ensure edge continuity and perform Canny
# (values selected experimentally, using trackbars)
img_blurred = (cv2.GaussianBlur(img.copy(), (2*2+1,2*2+1), 0))
canny = cv2.Canny(img_blurred, 35, 95)

# find first contours
_, cnts, _ = cv2.findContours(canny.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

# prepare black image to draw contours
canvas = np.ones(img.shape, np.uint8)
for c in cnts:
    l = cv2.arcLength(c, False)
    x,y,w,h = cv2.boundingRect(c)
    aspect_ratio = float(w)/h

    # filter "bad" contours (values selected experimentally)
    if l > 500:
        continue
    if l < 20:
        continue
    if aspect_ratio < 0.2:
        continue
    if aspect_ratio > 5:
        continue
    if l > 150 and (aspect_ratio > 10 or aspect_ratio < 0.1):
        continue
    # draw all the other contours
    cv2.drawContours(canvas, [c], -1, (255, 255, 255), 2)

# perform closing and blurring, to close the gaps
canvas = close_image(canvas, (7,7))
img_blurred = cv2.GaussianBlur(canvas, (8*2+1,8*2+1), 0)
# smooth the edges a bit to make sure canny will find continuous edges
img_blurred = smoother_edges(img_blurred, (9,9))
kernel = np.ones((3,3), np.uint8)
# erode to make sure separate blobs are not touching each other
eroded = cv2.erode(img_blurred, kernel)
# perform necessary thresholding before Canny
_, im_th = cv2.threshold(eroded, 50, 255, cv2.THRESH_BINARY)
canny = cv2.Canny(im_th, 11, 33)

# find contours again. this time mostly the right ones
_, cnts, _ = cv2.findContours(canny.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# calculate the mean area of the contours' bounding rectangles
sum_area = 0
rect_list = []
for i,c in enumerate(cnts):
    rect = cv2.minAreaRect(c)
    _, (width, height), _ = rect
    area = width*height
    sum_area += area
    rect_list.append(rect)
mean_area = sum_area / len(cnts)

# choose only rectangles that fulfill requirement:
# area > mean_area*0.6
for rect in rect_list:
    _, (width, height), _ = rect
    box = cv2.boxPoints(rect)
    box = np.int0(box * 5)
    area = width * height

    if(area > mean_area*0.6):
        # shrink the rectangles, since the shadows and reflections
        # make the resulting rectangle a bit bigger
        # the value was guessed - might need refinig
        rect = shrink_rect(rect, 0.8)
        box = cv2.boxPoints(rect)
        box = np.int0(box * resize_times)
        cv2.drawContours(imgc, [box], 0, (0,255,0),1)

# resize for visualizing purposes
imgc = cv2.resize(imgc, None, imgc, fx = 0.5, fy = 0.5)
cv2.imshow("imgc", imgc)
cv2.imwrite("result3.png", imgc)
cv2.waitKey(0)
Run Code Online (Sandbox Code Playgroud)

总的来说,我认为这是一个非常有趣的问题,有点太大,无法在这里得到解答.我提出的方法将被视为道路标志,而不是完整的解决方案.基本的想法是:

  1. 自适应预处理.

  2. 查找轮廓两次:用于过滤,然后用于实际分类.

  3. 根据平均大小过滤blob.

谢谢你的乐趣和好运!


K.S*_*kar 5

这是我使用的代码:

import cv2
from sympy import Point, Ellipse
import numpy as np
x1='C:\\Users\\Desktop\\python\\stack_over_flow\\XsXs9.png'    
image = cv2.imread(x1,0)
image1 = cv2.imread(x1,1)
x,y=image.shape
median = cv2.GaussianBlur(image,(9,9),0)
median1 = cv2.GaussianBlur(image,(21,21),0)
a=median1-median
c=255-a
ret,thresh1 = cv2.threshold(c,12,255,cv2.THRESH_BINARY)
kernel=np.ones((5,5),np.uint8)
dilation = cv2.dilate(thresh1,kernel,iterations = 1)
kernel=np.ones((5,5),np.uint8)
opening = cv2.morphologyEx(dilation, cv2.MORPH_OPEN, kernel)
cv2.imwrite('D:\\test12345.jpg',opening)
ret,contours,hierarchy =    cv2.findContours(opening,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
c=np.size(contours[:])
Blank_window=np.zeros([x,y,3])
Blank_window=np.uint8(Blank_window)
for u in range(0,c-1):
    if (np.size(contours[u])>200):
        ellipse = cv2.fitEllipse(contours[u])
        (center,axes,orientation) =ellipse
        majoraxis_length = max(axes)
        minoraxis_length = min(axes)
        eccentricity=(np.sqrt(1-(minoraxis_length/majoraxis_length)**2))
        if (eccentricity<0.8):
             cv2.drawContours(image1, contours, u, (255,1,255), 3)
cv2.imwrite('D:\\marked.jpg',image1)
Run Code Online (Sandbox Code Playgroud)

这是输出图像

这里的问题是找到一个圆形的物体.这个简单的解决方案是基于找到每个轮廓的偏心率.被检测到的这些物体是水滴.

  • 我不认为这实际上解决了这个问题.这个答案的作者只使用了一些最简单的案例.这里的问题主要在于反射,不同背景和整体噪声.在我看来,这些操作将失败,至少有30%的案例显示在问题中.[使用其中一个案例的代码](http://imgur.com/s527pRM) (3认同)