使用Canny Edge Detection在python中使图像背景变白

问题描述

我想将此图像的背景更改为python中的白色背景。我尝试了canny边缘检测,但是很难找到产品顶部的边缘,如第二幅图所示。我尝试了不同的阈值,但这会导致更多的背景不是白色。这可能是由于图像中产品的顶部与背景颜色几乎相同。

是否有一种方法可以检测出这样的微小差异?我还尝试过在产品后面使用绿色屏幕,但是由于产品的反射状态,产品变成绿色。

这是我的代码:

import cv2
import numpy as np
from skimage import filters
import matplotlib.pyplot as plt
from os import listdir
from os.path import isfile,join

plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
plt.rcParams['figure.dpi'] = 200
#== Parameters =======================================================================
BLUR = 15
CANNY_THRESH_1 = 10
CANNY_THRESH_2 = 255
MASK_DILATE_ITER = 10
MASK_ERODE_ITER = 10
MASK_COLOR = (1.0,1.0,1.0) # In BGR format


#== Processing =======================================================================
mypath = "./images"
images = [f for f in listdir(mypath) if isfile(join(mypath,f))]
#-- Read image -----------------------------------------------------------------------
for image in images:
    img_loc = mypath + "/" + image
    img = cv2.imread(img_loc)
    # threshold
    img_thresh = img
    thresh = 180
    img_thresh[ img_thresh >= thresh ] = 255
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    #-- Edge detection -------------------------------------------------------------------
    edges = cv2.Canny(gray,CANNY_THRESH_1,CANNY_THRESH_2)
    edges = cv2.dilate(edges,None)
    edges = cv2.erode(edges,None)
    #-- Find contours in edges,sort by area ---------------------------------------------
    contour_info = []
    contours,_ = cv2.findContours(edges,cv2.RETR_LIST,cv2.CHAIN_APPROX_NONE)
    for c in contours:
        contour_info.append((
            c,cv2.isContourConvex(c),cv2.contourArea(c),))
    contour_info = sorted(contour_info,key=lambda c: c[2],reverse=True)
    max_contour = contour_info[0]
    mask = np.zeros(edges.shape)
    cv2.fillConvexPoly(mask,max_contour[0],(255))
    #-- Smooth mask,then blur it --------------------------------------------------------
    mask = cv2.dilate(mask,None,iterations=MASK_DILATE_ITER)
    mask = cv2.erode(mask,iterations=MASK_ERODE_ITER)
    mask = cv2.GaussianBlur(mask,(BLUR,BLUR),0)
    mask_stack = np.dstack([mask]*3)    # Create 3-channel alpha mask
    #-- Blend masked img into MASK_COLOR background --------------------------------------
    mask_stack  = mask_stack.astype('float32') / 255.0          # Use float matrices,img         = img.astype('float32') / 255.0                 #  for easy blending
    masked = (mask_stack * img) + ((1-mask_stack) * MASK_COLOR) # Blend
    masked = (masked * 255).astype('uint8')                     # Convert back to 8-bit 
    result_dir = "./results/" + image
    cv2.imwrite(result_dir,masked)           # Save

Before image

After image

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...