简体   繁体   English

如何使用 python、opencv 从粘贴在相机输入上的图像中删除背景

[英]How to remove background from a image pasted on camera input using python, opencv

In python Opencv, I wanted to paste a drum image over my camera input and I have succeeded in the work but, there is a problem, The drum image has a transparent background and when I paste it a black coloured background appears, I want the background black colour to not appear in the output.在 python Opencv 中,我想在我的相机输入上粘贴一个鼓图像,我已经成功完成了这项工作,但是有一个问题,鼓图像具有透明背景,当我粘贴它时会出现黑色背景,我想要背景黑色不会出现在 output 中。 I have seen many places but did not succeed and this is my last hope.我看过很多地方,但没有成功,这是我最后的希望。 Please help请帮忙

# Importing modules
import cv2
import numpy
import time
# Video_capture using cv2
image = cv2.VideoCapture(0)
while True:
    # reading images
    success, img = image.read()
    drums_img = cv2.imread('media/drums_IMG.png')
    # resize image
    img1 = cv2.resize(img,(500,500))
    drums_img1 = cv2.resize(drums_img,(300,300))
    x_offset = y_offset = 100

    img1[y_offset:y_offset + drums_img1.shape[0], x_offset:x_offset + drums_img1.shape[1]] = drums_img1
    # Next

    # showing image
    cv2.imshow("Virtual Drums",img1)
    cv2.waitKey(1)
import cv2
import numpy as np

transparent = cv2.imread('transparent.png', cv2.IMREAD_UNCHANGED).astype(np.float32)/255
background = cv2.imread('background.jpg', cv2.IMREAD_UNCHANGED).astype(np.float32)/255

def put_transparent_to_image(image, transparent, x, y):
    h_t, w_t, *_ = transparent.shape
    transparent_alpha = np.zeros(background.shape[:2])
    transparent_alpha[y:y+h_t, x:x+w_t] = transparent[:,:,3]
    transparent_canvas = np.zeros_like(background)
    transparent_canvas[y:y+h_t, x:x+w_t] = transparent[:,:,:3]
    image[:,:,0] *= (1-transparent_alpha)
    image[:,:,1] *= (1-transparent_alpha)
    image[:,:,2] *= (1-transparent_alpha)
    transparent_canvas[:,:,0] * transparent_alpha
    transparent_canvas[:,:,1] * transparent_alpha
    transparent_canvas[:,:,2] * transparent_alpha
    result = image + transparent_canvas
    return result

result = put_transparent_to_image(background, transparent, 200, 400)
cv2.imwrite("result.jpg", (result*255).astype(np.uint8))

示例背景图像 带有 Alpha 通道的示例图像 结果

The mixing is not perfect, but you can start there.混合并不完美,但你可以从那里开始。 Basic idea is that we know alpha channel of our transparent image, so we can基本思想是我们知道透明图像的 alpha 通道,所以我们可以

  • multiply our background image by (1-alpha channel)将我们的背景图像乘以(1-alpha 通道)
  • multiply our transparent image by alpha channel将我们的透明图像乘以Alpha 通道
  • sum the two images.将两个图像相加。

We assume alpha channel has values 0-1.我们假设 alpha 通道的值是 0-1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM