python - 去掉边缘的黑线

标签 python opencv image-thresholding

我有一个检测地板的程序,所以我检测到的地板被移除并变成透明的png,但边缘仍然有黑线

before adding threshold

enter image description here

enter image description here

src = cv2.imread(file_name)
    
tmp = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
_,alpha = cv2.threshold(tmp,0, 255, cv2.THRESH_BINARY)
 b, g, r = cv2.split(src)
 rgba = [b,g,r, alpha]
 dst = cv2.merge(rgba,1)
    

最佳答案

您可以通过对 alpha channel 进行抗锯齿来减轻 Python/OpenCV/Skimage 中黑色过渡线的影响,如下所示:

  • 使用 alpha 读取图像
  • 提取 bgr 基础图像
  • 提取 alpha channel
  • 高斯模糊 alpha channel (选择模糊量以匹配黑色过渡)
  • 拉伸(stretch) alpha channel 的动态范围,使 255 -> 255 和中灰变为 0 并保存为 mask 。 (选择中灰度级进一步减轻)
  • 将生成的mask图像放入bgr图像的alpha channel
  • 保存结果

输入:

enter image description here

import cv2
import numpy as np
import skimage.exposure

# load image with alpha
img = cv2.imread('room.png', cv2.IMREAD_UNCHANGED)

# extract only bgr channels
bgr = img[:, :, 0:3]

# extract alpha channel
alpha = img[:, :, 3]

# apply Gaussian blur to alpha
blur = cv2.GaussianBlur(alpha, (0,0), sigmaX=5, sigmaY=5, borderType = cv2.BORDER_DEFAULT)

# stretch so that 255 -> 255 and 192 -> 0
mask = skimage.exposure.rescale_intensity(blur, in_range=(192,255), out_range=(0,255)).astype(np.uint8)

# put mask into alpha channel
result = np.dstack((bgr, mask))

# save result
cv2.imwrite('room_new_alpha.png', result)

# display result, though it won't show transparency
cv2.imshow("bgr", bgr)
cv2.imshow("alpha", alpha)
cv2.imshow("mask", mask)
cv2.imshow("result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

结果:

enter image description here

关于python - 去掉边缘的黑线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71836631/

相关文章:

c++ - 为什么 cv::findContours 返回这么多轮廓?

python - 如何知道在findContour之后是否需要反转阈值类型

python - C++ boost + Python : undefined reference to Py_Dealloc

c - 无法在 OpenCV 中检测网络摄像头

python - 完美正方形 leetcode 缺少带有递归解决方案的测试用例

c# - 优化求和 2 个字节数组

linux - 在 ubuntu14.01 上安装 opencv 2.4.9 出错

python - 将 openCV-python 自适应阈值应用于 3D tiff

python - 为什么 sys.modules 中有虚拟模块?

python - 使用 cx_freeze : can I generate all apps from one platform? 在 Mac、Linux 和 Windows 上分发 python