[英]How to add an image to a video using OpenCv in Python?
我试图通过修改我在网上找到的代码(用于合并两张图片),使用 OpenCv 为我的视频添加徽标。 该过程以某种方式起作用,但添加的徽标仅显示了四分之一,而不是完整的。 所以我的问题是:
任何帮助或文档(对于初学者)将不胜感激。
我使用的代码:
import cv2
import numpy as np
foreground = cv2.imread('logo.jpg')
cap = cv2.VideoCapture("video.mp4")
alpha = 0.4
while True:
ret, background = cap.read()
background = cv2.flip(background,1)
added_image = cv2.addWeighted(background[150:250,150:250,:],alpha,foreground[0:100,0:100,:],1-alpha,0)
background[150:250,150:250] = added_image
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(background,'alpha:{}'.format(alpha),(10,30), font, 1,(255,255,255),2,cv2.LINE_AA)
cv2.imshow('a',background)
k = cv2.waitKey(10)
if k == ord('q'):
break
if k == ord('a'):
alpha +=0.1
if alpha >=1.0:
alpha = 1.0
elif k== ord('d'):
alpha -= 0.1
if alpha <=0.0:
alpha = 0.0
cap.release()
cv2.destroyAllWindows()
我在你的代码中添加了注释和一些易于使用的东西,以帮助更容易理解每个部分应该做什么。 整体结构是相同的,但希望这可以帮助您弄清楚为什么覆盖看起来是这样的。
import cv2
import numpy as np
# load image and start video
foreground = cv2.imread('logo.jpg')
cap = cv2.VideoCapture("video.mp4")
# init font
font = cv2.FONT_HERSHEY_SIMPLEX
# position of logo on video
top_left = [0, 0] # the top-left corner of your logo goes here
tx = top_left[0] # less typing later
ty = top_left[1]
# crop of logo
left = 0
right = 100
top = 0 # y = 0 is the top of the image
bottom = 100
# calculate width and height of logo crop
width = right - left
height = bottom - top
# main loop
alpha = 0.4
while True:
# read image
ret, background = cap.read()
# horizontal flip to create mirror image
background = cv2.flip(background,1)
# quick primer on 2d image slicing:
# images are [y,x]
# crop = image[0:100, 300:500] will be a 200x100 image (width x height)
# the logo slice should give you a decent idea of what's going on
# WARNING: there are no out-of-bounds checks here, make sure that
# tx + width is less than the width of the background
# ty + height is less than the height of the background
# right is less than the width of the foreground
# bottom is less than the height of the foreground
# get crops of background and logo
background_slice = background[ty:ty+height, tx:tx+width];
logo_slice = foreground[top:bottom, left:right];
# since we don't change our crop, we could do the logo slice outside the loop
# but I'll keep it here for clarity
# add slice of logo onto slice of background
added_image = cv2.addWeighted(background_slice,alpha,logo_slice,1-alpha,0)
background[ty:ty+height, tx:tx+width] = added_image
# draw alpha value
cv2.putText(background,'alpha:{}'.format(alpha),(10,30), font, 1,(255,255,255),2,cv2.LINE_AA)
# show image
cv2.imshow('a',background)
k = cv2.waitKey(10)
# process keypresses
if k == ord('q'):
break
if k == ord('a'):
alpha +=0.1
if alpha >=1.0:
alpha = 1.0
elif k== ord('d'):
alpha -= 0.1
if alpha <=0.0:
alpha = 0.0
# close
cap.release()
cv2.destroyAllWindows()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.