如何使用OpenCV检测图像中的波纹

时间:2019-05-03 18:07:53

标签: python numpy opencv

所以我有一张沙丘的图片,目前看起来像这样。enter image description here

我想做的是使用Python中的opencv识别图片中的波纹。我只是在学习这个库,所以我不知道该库中的所有怪癖。我做了一些研究,但找不到类似的问题,这特别困难,因为涟漪会产生阴影。我的预期结果应该与此相反,与所有其他功能相比,所有涟漪都更加突出。下面是一个男人的肖像,头发突出。我想对下面的沙丘中的涟漪做同样的事情。

enter image description here 下面的代码是我的基本知识,这是我最终产品的输出,但仍需要一些工作。

 path = "C:/some path//to get//to my picture//Dune field_resize.jpg"


# image I'm using
img = cv2.imread ( path , cv2.IMREAD_GRAYSCALE )
kernel = np.ones ( (5 , 5) , np.uint8 )

# Canny edge detecting
edges = cv2.Canny ( img , 75 , 200 )
th , img = cv2.threshold ( img , 220 , 255 , cv2.THRESH_BINARY_INV );

# Copy the thresholded image.
img_floodfill = img.copy ()

# Mask used to flood filling.
# Notice the size needs to be 2 pixels than the image.
h , w = img.shape[:2]
mask = np.zeros ( (h + 2 , w + 2) , np.uint8 )

# Floodfill from point (0, 0)
cv2.floodFill ( img_floodfill , mask , (0 , 0) , 255 );

# Invert floodfilled image
img_floodfill_inv = cv2.bitwise_not ( img_floodfill )

# Combine the two images to get the foreground.
img_out = img | img_floodfill_inv

# Display images.
cv2.imwrite ( "Thresholded Image.png" , img )
cv2.imwrite ( "Floodfilled Image.png" , img_floodfill )
cv2.imwrite ( "Inverted Floodfilled Image.png" , img_floodfill_inv )
cv2.imwrite ( "Foreground.png" , img )
cv2.waitKey ( 0 )

cv2.imwrite ( "canny_edge.png" , edges )

img_erosion = cv2.erode ( img , kernel , iterations=1 )

cv2.waitKey ( 0 )
cv2.destroyAllWindows ()

enter image description here

1 个答案:

答案 0 :(得分:4)

这是使用一些过滤的简单方法

  • 将图像转换为灰度
  • 使用Canny边缘检测来找到边缘
  • 找到轮廓
  • 为每个轮廓找到其面积并使用最大阈值面积进行过滤

Canny

enter image description here

检测到的波纹

enter image description here

您可能需要调整cv2.Canny或阈值区域参数。在检测到Canny之后进行过滤的另一种可能方法是distinguish between straight and irregular lines。可能有更好的滤波方法,但是这种简单的面积方法可以吸收大部分波纹。

import cv2
import numpy as np

original_image = cv2.imread('1.jpg')
gray = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY)

canny = cv2.Canny(gray, 50, 150)
cnts = cv2.findContours(canny.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]

threshold_max_area = 165
for c in cnts:
    area = cv2.contourArea(c)
    if area < threshold_max_area:
        cv2.drawContours(original_image,[c], 0, (0,255,0), 1)

cv2.imshow('canny', canny)
cv2.imshow('found', original_image)

cv2.waitKey(0)
cv2.destroyAllWindows()