在噪声很大的二进制图像上检测圆形形状

时间:2019-01-24 12:20:21

标签: python image opencv machine-learning detection

我试图几乎完全通过使用OpenCV(在Python中)使用图像预处理技术来检测黑白足球。我的想法如下;

  1. 处理图像(例如,处理模糊的二进制照片)
  2. 找到足球的多个“候选对象”(例如通过轮廓检测)
  3. 在一个非常简单的神经网络中将这些候选对象的大小调整为48x48px,并输入其像素对应的布尔值(0 =黑色像素,1 =白色像素),然后为每个候选对象输出置信度值
  4. 确定照片中是否存在足球以及最可能的位置

我坚持寻找合适的人选。目前,这是我的方法;

Step 1: The original image

Step 2: The blurred image (medianblur, kernel 7)

第3步:Generated binary image A Generated binary image B

然后,我使用findContours在二进制图像上查找轮廓。如果未在二进制图像B上找到候选(使用最小和最大边界框阈值),则findContours将在二进制图像A上运行(并将返回候选)。如果在二进制图像B上找到一个或多个候选图像,则原始图像将被重新模糊(使用内核15),而二进制图像C将用于查找轮廓并返回候选图像。参见:Generated binary image C

这是用于生成这些二进制图像的代码:

def generateMask(imgOriginal, rgb, margin):
  lowerLimit = np.asarray(rgb)
  upperLimit = lowerLimit+margin

  # switch limits if margin is negative
  if(margin < 0):
    lowerLimit, upperLimit = upperLimit, lowerLimit

  mask = cv.inRange(imgOriginal, lowerLimit, upperLimit)

  return mask

# generates a set of six images with (combinations of) mask(s) applied
def applyMasks(imgOriginal, mask1, mask2):
  # applying both masks to original image
  singleAppliedMask1 = cv.bitwise_and(imgOriginal, imgOriginal, mask = mask1) #res3
  singleAppliedMask2 = cv.bitwise_and(imgOriginal, imgOriginal, mask = mask2) #res1

  # applying masks to overlap areas in single masked and original image
  doubleAppliedMaskOv1 = cv.bitwise_and(
    imgOriginal,
    singleAppliedMask1,
    mask = mask2
  ) #res4
  doubleAppliedMaskOv2 = cv.bitwise_and(
    imgOriginal,
    singleAppliedMask2,
    mask = mask1
  ) #res2

  # applying masks to joint areas in single masked and original image
  doubleAppliedMaskJoin1 = cv.bitwise_or(
    imgOriginal, 
    singleAppliedMask1, 
    mask = mask2
  ) #res7
  doubleAppliedMaskJoin2 = cv.bitwise_or(
    imgOriginal,
    singleAppliedMask2,
    mask = mask1
  ) #res6

  return (
    singleAppliedMask1, singleAppliedMask2,
    doubleAppliedMaskOv1, doubleAppliedMaskOv2,
    doubleAppliedMaskJoin1, doubleAppliedMaskJoin2
  )

def generateBinaries(appliedMasks):
  # variable names correspond to output variables in applyMasks()
  (sam1, sam2, damov1, damov2, damjo1, damjo2) = appliedMasks

  # generate thresholded images
  (_, sam1t) = cv.threshold(sam1, 0, 255, cv.THRESH_BINARY_INV)
  (_, sam1ti) = cv.threshold(sam1, 0, 255, cv.THRESH_BINARY_INV)
  (_, sam2t) = cv.threshold(sam2, 0, 255, cv.THRESH_BINARY)
  (_, sam2ti) = cv.threshold(sam2, 0, 255, cv.THRESH_BINARY_INV)

  (_, damov1t) = cv.threshold(damov1, 0, 255, cv.THRESH_BINARY)
  (_, damov2t) = cv.threshold(damov2, 0, 255, cv.THRESH_BINARY_INV)

  (_, damjo1t) = cv.threshold(damjo1, 0, 255, cv.THRESH_BINARY_INV)
  (_, damjo2t) = cv.threshold(damjo2, 0, 255, cv.THRESH_BINARY)

  # return differences in binary images
  return ((damov2t-sam2t), (sam1t-damov1t), (sam2ti-damjo2t))

此示例图像中的结果很好,而且非常有用,即使看起来很错误:see result

很容易获得更好的示例图像结果(例如,仅返回一个或两个候选对象,其中包括一个用于足球的完美包围盒),但是,在对参数I进行大量参数调整之后在此示例中使用的方法似乎能产生最佳的整体召回效果。

但是,我非常迷恋某些照片,这些照片将显示原始图像,二进制A和B图像(基于内核7所模糊的原始图像中值生成)和二进制C图像(15内核) 。目前,我的方法平均每张照片返回约15个候选者,其中25%的照片至少包含一个完美的球边界框,而约75%的照片至少包含 strong>包含一个部分正确的包围盒(例如,在包围盒中有一块球,或者仅仅是一部分球)。

Original images + binary images A

Binary images B + binary images C

(我最多只能发布8个链接)

希望大家能就如何进行提供一些建议。

2 个答案:

答案 0 :(得分:0)

您还可以使用blackhat和tophat形态学运算法在白色部分中找到嵌套的球形黑色部分。它会比阈值更强大。

答案 1 :(得分:0)

如何执行此操作有很多可能性。可能使用神经网络是一个不错的选择,但是您仍然需要了解并训练其中的一项以完成任务。

您可以使用阈值化和高斯模糊,作为建议,我可以使用归一化互相关来添加模板匹配。基本上,您需要一个模板(一个球的图像,或者甚至更好的是,一组不同尺寸的图像,因为球的位置可能会有所不同)。

然后在图像上进行迭代,并检查模板是否匹配。当然,这不适用于遮挡的图像,但可能有助于获得一些候选对象。

本文(https://ieeexplore.ieee.org/document/5375779)或幻灯片(http://www.cse.psu.edu/~rtc12/CSE486/lecture07.pdf)中有关上述过程的更多详细信息。

我写了一小段代码向您展示这个想法。只是从图像中裁剪了球(所以我被骗了,但这只是为了展示想法)。它也仅使用球和图像之间的差异,而更复杂的度量(如NCC)会更好,但正如所说的,这是一个例子。

The ball cropped <-球被割破

import matplotlib.pyplot as plt
import numpy as np
import pdb
import cv2

def rgb2gray(rgb):

    r, g, b = rgb[:,:,0], rgb[:,:,1], rgb[:,:,2]
    gray = 0.2989 * r + 0.5870 * g + 0.1140 * b

    return gray

if __name__ == "__main__":

    ball = plt.imread('ball.jpg');
    ball = rgb2gray(ball);
    findtheballcol = plt.imread('findtheball.jpg');
    findtheball = rgb2gray(findtheballcol)
    matching_img = np.zeros((findtheball.shape[0], findtheball.shape[1]));

    #METHOD 1
    width = ball.shape[1]
    height = ball.shape[0]
    for i in range(ball.shape[0], findtheball.shape[0]-ball.shape[0]):
        for j in range(ball.shape[1], findtheball.shape[1]-ball.shape[1]):


            # here use NCC or something better
            matching_score = np.abs(ball - findtheball[i:i+ball.shape[0], j:j+ball.shape[1]]);
            # inverting so that max is what we are looking for
            matching_img[i,j] = 1 / np.sum(matching_score);


    plt.subplot(221);
    plt.imshow(findtheball); 
    plt.title('Image')
    plt.subplot(222);
    plt.imshow(matching_img, cmap='jet');
    plt.title('Matching Score')
    plt.subplot(223);
    #pick a threshold
    threshold_val = np.mean(matching_img) * 2; #np.max(matching_img - (np.mean(matching_img)))
    found_at = np.where(matching_img > threshold_val)
    show_match = np.zeros_like(findtheball)
    for l in range(len(found_at[0])):
        yb = round(found_at[0][l]-height/2).astype(int)
        yt = round(found_at[0][l]+height/2).astype(int)
        xl = round(found_at[1][l]-width/2).astype(int)
        xr = round(found_at[1][l]+width/2).astype(int)
        show_match[yb: yt, xl: xr] = 1;
    plt.imshow(show_match)
    plt.title('Candidates')
    plt.subplot(224)
    # higher threshold
    threshold_val = np.mean(matching_img) * 3; #np.max(matching_img - (np.mean(matching_img)))
    found_at = np.where(matching_img > threshold_val)
    show_match = np.zeros_like(findtheball)
    for l in range(len(found_at[0])):
        yb = round(found_at[0][l]-height/2).astype(int)
        yt = round(found_at[0][l]+height/2).astype(int)
        xl = round(found_at[1][l]-width/2).astype(int)
        xr = round(found_at[1][l]+width/2).astype(int)
        show_match[yb: yt, xl: xr] = 1;
    plt.imshow(show_match)
    plt.title('Best Candidate')
    plt.show()

Result on your image

玩得开心!