【问题标题】:How can I contour low-contrast objects in python?如何在 python 中勾勒出低对比度对象的轮廓?
【发布时间】:2021-01-23 02:01:55
【问题描述】:

我很难勾勒出此类低对比度物体的轮廓:

我的目标是输出如下:

在上面的示例中,我使用cv2.findContours 和下面的代码,但使用的阈值是105 ret,thresh = cv.threshold(blur, 105, 255, 0)。但是,如果我为低对比度图像重现它,我无法找到最佳阈值:

import numpy as np
from PIL import Image
import requests
from io import BytesIO
import cv2 as cv

url = 'https://i.stack.imgur.com/OeZJ9.jpg'
response = requests.get(url)

img = Image.open(BytesIO(response.content)).convert('RGB')
img = np.array(img) 

imgray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

blur = cv.GaussianBlur(imgray, (105, 105), 0)
        
ret,thresh = cv.threshold(blur, 205, 255, 0)
im2, cnts, hierarchy = cv.findContours(thresh,cv.RETR_TREE,cv.CHAIN_APPROX_SIMPLE)
cv.drawContours(img, cnts, -1, (0,0,255), 5)
plt.imshow(img, cmap = 'gray')

输出:

我知道问题是背景和对象的强度重叠,但我找不到任何其他成功的方法。我尝试过的其他事情包括:

  1. 阈值,in skimageskimage.measure.find_contours
  2. 分水岭算法,in opencv
  3. 侵蚀和扩张in opencv,这会降低过多的轮廓分辨率。

我希望能帮助您以尽可能高的分辨率对与背景对比度较低的对象进行轮廓绘制。

【问题讨论】:

  • 你可能有一些按纹理分割的运气
  • 你知道物体在哪里,比如底部、顶部、中心

标签: python opencv image-processing computer-vision edge-detection


【解决方案1】:

喏,

为了解决您的问题,我会使用这个 sn-p 检测轮廓并在其区域上过滤它们,只留下大于给定大小的轮廓。在你的情况下,我假设你只是在搜索一个对象,但我准备好将代码扩展到具有多个对象的图片

import cv2
import numpy as np


# input image
path = "16.jpg"

# finding contours
def getContours(img, imgContour):    

    contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    
    finalContours = []
    
    # for each contour found
    for cnt in contours:
        # find its area in pixel^2
        area = cv2.contourArea(cnt)
        print("Contour area: ", area)

        # fixed assuming you are searching for the biggest object
        # value can be found via previous print
        minArea = 18000
        
        if (area > minArea):

            perimeter = cv2.arcLength(cnt, False)
            
            # smaller epsilon -> more vertices detected [= more precision]
            # improving bounding box precision - original value 0.02 * perimeter
            epsilon = 0.002*perimeter
            # check how many vertices         
            approx = cv2.approxPolyDP(cnt, epsilon, True)
            print(len(approx))
            
            finalContours.append([len(approx), area, approx, cnt])

    # leaving this part if you have more objects to detect
    # not needed when minArea has been chosen to detect only one object
    # sorting the final results in descending order depending on the area
    finalContours = sorted(finalContours, key = lambda x:x[1], reverse=True)
    print("Final Contours number: ", len(finalContours))
    
    for con in finalContours:
        cv2.drawContours(imgContour, con[3], -1, (0, 0, 255), 3)

    return imgContour, finalContours

 
# sourcing the input image
img = cv2.imread(path)
# img.shape gives back height, width, color in this order
original_height, original_width, color = img.shape 
print('Original Dimensions : ', original_width, original_height)

# resizing to see the entire image
scale_percent = 30
width = int(original_width * scale_percent / 100)
height = int(original_height * scale_percent / 100)
print('Resized Dimensions : ', width, height)

dim = (width, height)
# resize image
resized = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)
cv2.imshow("Starting image", resized)
cv2.waitKey()

# blurring
imgBlur = cv2.GaussianBlur(resized, (7, 7), 1)
# graying
imgGray = cv2.cvtColor(imgBlur, cv2.COLOR_BGR2GRAY)

# inizialing thresholds
threshold1 = 14
threshold2 = 17

# canny
imgCanny = cv2.Canny(imgGray, threshold1, threshold2)
# showing the last produced result
cv2.imshow("Canny", imgCanny)
cv2.waitKey()

kernel = np.ones((2, 2))
imgDil = cv2.dilate(imgCanny, kernel, iterations = 3)
imgThre = cv2.erode(imgDil, kernel, iterations = 3)

imgFinalContours, finalContours = getContours(imgThre, resized)

# show the contours on the unfiltered resized image
cv2.imshow("Final Contours", imgFinalContours)
cv2.waitKey()
cv2.destroyAllWindows()

使用所选值运行此程序的最终输出如下:


祝你有美好的一天,
安东尼诺

【讨论】:

  • 非常感谢您的回复。我对我的数据集的低对比度对象执行了您的 sn-p,它适用于其中一些已经成功的对象。另一方面,它并不适用于所有人(例如,i.stack.imgur.com/hvVRX.jpg)。我意识到在您的代码中,有多种方法可以调整参数,因此我需要做更多的工作;也许有一种方法可以一次获得所有轮廓。无论如何,非常感谢,Ciao!
  • @db_max:是的,正确的。您可能需要调整参数,因为每张图片都不同,并且可能有不同的条件 [对比度、背景、照明、要检测的对象的大小等]。此外,鉴于您提出的问题已得到解决,如果您可以将我的回答标记为解决您的问题的答案,那将是一种友好且受欢迎的方式。祝你有美好的一天
【解决方案2】:

这里提出了什么

通过颜色梯度变化进行轮廓检测(参见 Antonino 的回复)

对背景对比度低的对象进行轮廓处理并非易事。虽然 Antonino 的 sn-p 接近轮廓,但对于轮廓检测来说还不够:

  • finalContours 不是一条单一的等高线,而是一组不清楚的线,即使使用了最好的参数(见下文):

  • 为了找到可能的最佳参数,我使用了下面的伪代码,它输出了数千张经过视觉分类的图像(参见输出图像)。但是,可能的参数组合都没有成功,即输出所需的轮廓:

     for scale_percent in range(30,51,5):
         for threshold1 in range(5, 21):
             for threshold2 in range(10,31):
                 for gauss_kernel in range(1,11,2):
                     for std in [0,1,2]:
                         for kernel_size in range(2,6):
                             for iterations_dialation in [2,3]:
                                 for iterations_erosion in [2,3]:
                                     for img in images:
                                         name = img[3:]
                                         img = cv2.imread('my/img/dir'+img)
    
                                         original_height, original_width, color = img.shape 
                                         width = int(original_width * scale_percent / 100)
                                         height = int(original_height * scale_percent / 100)
    
                                         dim = (width, height)
                                         resized = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)
    
                                         imgBlur = cv2.GaussianBlur(resized, (gauss_kernel, gauss_kernel), std)
    
                                         imgGray = cv2.cvtColor(imgBlur, cv2.COLOR_BGR2GRAY)
    
                                         imgCanny = cv2.Canny(imgGray, threshold1, threshold2)
    
                                         plt.subplot(231),plt.imshow(resized), plt.axis('off')
                                         plt.title('Original '+ str(name))    
    
                                         plt.subplot(232),plt.imshow(imgCanny,cmap = 'gray')
                                         plt.title('Canny Edge-detector\n thr1 = {}, thr2 = {}'.format(threshold1, threshold2)), plt.axis('off')
    
                                         kernel_s = (kernel_size, kernel_size)
                                         kernel = np.ones(kernel_s)
    
                                         imgDil = cv2.dilate(imgCanny, kernel, iterations = iterations_dialation)
                                         plt.subplot(233),plt.imshow(imgDil, cmap = 'gray'), plt.axis('off')
                                         plt.title("Dilated\n({},{}) iterations = {}".format(kernel_size, kernel_size,
                                                                                             iterations_dialation))
    
                                         kernel_erosion = np.ones(())
                                         imgThre = cv2.erode(imgDil, kernel, iterations = iterations_erosion)
                                         plt.subplot(234),plt.imshow(imgThre, cmap = 'gray'), plt.axis('off')
                                         plt.title('Eroded\n({},{}) iterations = {}'.format(kernel_size, kernel_size, 
                                                                                            iterations_erosion))
    
                                         imgFinalContours, finalContours = getContours(imgThre, resized)
    
                                         plt.subplot(235), plt.axis('off')
                                         plt.title("Contours")
    
                                         plt.subplot(236), plt.axis('off')
                                         plt.title('Contours')
    
                                         plt.tight_layout(pad = 0.1)
    
                                         plt.imshow(imgFinalContours) 
    
                                         plt.savefig("my/results/"
                                                     +name[:6]+"_scale_percent({})".format(scale_percent)+
                                                     "_threshold1({})".format(threshold1)
                                                    +"_threshold2({})".format(threshold2)
                                                    +"_gauss_kernel({})".format(gauss_kernel)
                                                    +"_std({})".format(std)
                                                    +"_kernel_size({})".format(kernel_size)
                                                    +"_iterations_dialation({})".format(iterations_dialation)
                                                    +"_iterations_erosion({})".format(iterations_erosion)
                                                    +".jpg")
                                         plt.title(name)
    
     images = ["b_36_2.jpg", "b_78_2.jpg", "b_51_2.jpg","b_72_2.jpg", "a_78_2.jpg", "a_70_2.jpg"]
     process_images_1(images)
    

输出:

解决办法

使用预训练的深度学习模型

最初的想法是使用 Grabcut 来训练模型,但这在时间上会非常昂贵。因此,预训练的深度学习模型是第一枪。虽然一些工具failed,但这个other tool 优于之前尝试过的任何其他方法(见下图)。因此,GitHub 存储库的创建者的所有功劳,延伸到操作模型(U^2-NET、BASNet)的创建者。 https://github.com/OPHoperHPO/image-background-remove-tool 不需要任何图像预处理,包含有关如何部署它的非常简单的文档,甚至是可执行的 google colab 笔记本。输出图像是具有透明背景的 png 图像: 因此,找到轮廓所需要的只是隔离 alpha 通道:

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

filename = '/a_58_2_pg_0.png'
image_4channel = cv2.imread(filename, cv2.IMREAD_UNCHANGED)
alpha_channel = image_4channel[...,-1]
contours, hier = cv2.findContours(alpha_channel, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

for idx,contour in enumerate(contours):

        # create mask
        # zeros with same shape
        mask = np.zeros(alpha_channel.shape,np.uint8)
        
        # draw contour
        mask = cv2.drawContours(mask,[contour],-1,(255,255,255),-1) # -1 to fill the mask
        cv2.imwrite('/contImage.jpg', mask)
        plt.imshow(mask)

【讨论】:

    猜你喜欢
    • 2019-03-28
    • 2019-04-23
    • 1970-01-01
    • 2015-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-22
    • 1970-01-01
    相关资源
    最近更新 更多