如何在python中绘制低对比度对象的轮廓?

如何解决如何在python中绘制低对比度对象的轮廓?

我很难勾勒出这种类型的低对比度对象:

a low-contrast plagioclase

我希望输出诸如以下内容的

enter image description here

在上面的示例中,我将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,205,0)
im2,cnts,hierarchy = cv.findContours(thresh,cv.RETR_TREE,cv.CHAIN_APPROX_SIMPLE)
cv.drawContours(img,-1,(0,255),5)
plt.imshow(img,cmap = 'gray')

输出:

contour not achieved

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

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

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

解决方法

这里提出了什么

通过颜色渐变变化检测轮廓(见 Antonino 的回复)

对背景对比度低的对象进行轮廓绘制并非易事。尽管 Antonino 的片段接近轮廓,但对于轮廓检测还不够:

  • finalContours 不是单条轮廓线,而是一系列不清晰的线,即使使用最佳参数(见下文): enter image description here

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

     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,iterations = iterations_erosion)
                                         plt.subplot(234),plt.imshow(imgThre,plt.axis('off')
                                         plt.title('Eroded\n({},{}) iterations = {}'.format(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)
    

输出: enter image description here

解决办法

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

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

enter image description here

,

Ciao

为了解决您的问题,我将使用该片段来检测轮廓,并在其区域上对其进行过滤,仅保留大于给定尺寸的轮廓。在您的情况下,我假设您仅在搜索对象,但我准备将代码扩展为包含多个对象的图片

import cv2
import numpy as np


# input image
path = "16.jpg"

# finding contours
def getContours(img,imgContour):    

    contours,hierarchy = cv2.findContours(img,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],(0,3)

    return imgContour,finalContours

 
# sourcing the input image
img = cv2.imread(path)
# img.shape gives back height,width,color in this order
original_height,color = img.shape 
print('Original Dimensions : ',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 : ',height)

dim = (width,height)
# resize image
resized = cv2.resize(img,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,threshold2)
# showing the last produced result
cv2.imshow("Canny",imgCanny)
cv2.waitKey()

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

imgFinalContours,resized)

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

使用选定的值运行此命令的最终输出如下:

snippet_output


祝你有美好的一天
安东诺

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)> insert overwrite table dwd_trade_cart_add_inc > select data.id, > data.user_id, > data.course_id, > date_format(
错误1 hive (edu)> insert into huanhuan values(1,'haoge'); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive> show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 <configuration> <property> <name>yarn.nodemanager.res