簡體   English   中英

如何在opencv中將png img添加到實時相機提要中?

[英]How to add a png img to live camera feed in opencv?

我正在嘗試使用 opencv 在來自我的網絡攝像頭的框架上顯示 png。 我該怎么做呢?

PNG:

在此處輸入圖片說明

代碼:

import cv2
cam= cv2.VideoCapture(0)
wounded_img= cv2.imread("media/wounded.png", 0)
while True:
    ret, frame = cam.read()
    # How do i add wounded.png to the bottom of this frame?
    cv2.imshow("Cam",frame)
    if cv2.waitKey(1) & 0xFF == ord("q"):
            break

cam.release()
    cv2.destroyAllWindows()

這有點微不足道,但很乏味,所以我只會解釋它應該如何工作。

您的“框架”變量應該是 ??? X ??? x 3 numpy 數組(還有wounded_img 變量。)(每個??? x ??? 都是B、G、R 通道。)您可以簡單地用“wounded_img”中的值覆蓋“frame”變量數組的一部分“ 大批。

不過,您可以考慮先通過 cv2.resize 調整大小。

編輯:這是一個示例代碼。 你可以盡可能地適應它。 我基本上只是調整了大小並截斷了您要添加的圖像,用您嘗試添加的圖像替換圖像中的部分數組。

您可以對每一幀執行此操作。

這是我正在使用的貓的圖像。

下面是一個例子:

import cv2 as cv
import numpy as np

#For resizing image
def rescaleFrame(frame, scale=0.75):
    width = int(frame.shape[1] * scale)
    height = int(frame.shape[0] * scale)
    dimensions = (width,height)

    return cv.resize(frame,dimensions,interpolation=cv.INTER_AREA)

img = cv.imread('cat.jpg')
wounded_img =cv.imread('wounded.png')
wounded_img_rescaled = rescaleFrame(wounded_img,0.3)

#I checked while debugging that this is the range that removes the black background (if that was what you are looking for)
wounded_img_rescaled_cut = wounded_img_rescaled[82:116,117:282]
img[img.shape[0] - 34:img.shape[0],img.shape[1]-165:img.shape[1]] = wounded_img_rescaled_cut
#34 and 165 came from the height and width of the image being added

cv.imshow('With Wounded Logo',img)

cv.waitKey(0)

輸出: 在這里,在右側。

我從其他地方得到了這個代碼,我修改了它。 這有效。

import cv2

# load the overlay image. size should be smaller than video frame size
img = cv2.imread('media/wounded.png')

# Get Image dimensions
img_height, img_width, _ = img.shape

# Start Capture
cap = cv2.VideoCapture(0)

# Get frame dimensions
frame_width  = cap.get(cv2.CAP_PROP_FRAME_WIDTH )
frame_height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT )

# Print dimensions
print('image dimensions (HxW):',img_height,"x",img_width)
print('frame dimensions (HxW):',int(frame_height),"x",int(frame_width))

# Decide X,Y location of overlay image inside video frame. 
# following should be valid:
#   * image dimensions must be smaller than frame dimensions
#   * x+img_width <= frame_width
#   * y+img_height <= frame_height
# otherwise you can resize image as part of your code if required

x = 50
y = 50

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    # add image to frame
    frame[ y:y+img_height , x:x+img_width ] = img

    # Display the resulting frame
    cv2.imshow('frame',frame)

    # Exit if ESC key is pressed
    if cv2.waitKey(20) & 0xFF == 27:
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM