########## 返回目录 - 信息隐藏技术(Python) ###
预期效果
import cv2
import numpy as np
def frame_pip(frame1, frame2, N, w):
"Add frame2 at the top-right corner of frame1"
" N - the size of the top-left region"
" w - weight og frame 2"
offset_y = 10 # offset ot the top border
offset_x = 20 # offset ot the right border
frame2_resized = cv2.resize(frame2, (N, N))
# Generate a circle type mask
logo_region_mask = np.zeros((N, N, 3), dtype = np.uint8)
# 在logo_region_mask中,以(N,N)为圆心,以N为半径画一个实心圆
cv2.circle(logo_region_mask, (np.int(N/2),np.int(N/2)), np.int(N/2), (1,1,1), -1)
region_tmp = w*frame2_resized + (1-w)*frame1[offset_y:(N+offset_y), -(N+offset_x):-offset_x, :]
region_tmp = region_tmp.astype(np.uint8)
# 先生成一个小区域logo_region
logo_region = frame1[offset_y:(N+offset_y), -(N+offset_x):-offset_x, :]
logo_region[logo_region_mask>0] = region_tmp[logo_region_mask>0]
# 把小区域logo_region的值更新回img_marked
frame1[offset_y:(N+offset_y), -(N+offset_x):-offset_x, :] = logo_region
frame1 = frame1.astype(np.uint8)
vid_file = './video/football_ntsc.mp4'
# 1. open a video and the camera
vid_reader = cv2.VideoCapture(vid_file)
vid_capture = cv2.VideoCapture(0)
fps = 30
sz = (int(vid_reader.get(cv2.CAP_PROP_FRAME_WIDTH)),
int(vid_reader.get(cv2.CAP_PROP_FRAME_HEIGHT)))
# 2. Open an video writer in mp4 format
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
vid_writer = cv2.VideoWriter()
vid_writer.open('vid_pip.mp4', fourcc, fps, sz, True)
while(vid_reader.isOpened() and vid_capture.isOpened()):
ret1, frame1 = vid_reader.read() # 读视频一帧
ret2, frame2 = vid_capture.read() # 读摄像头一帧
if not(ret1) or not(ret2):
break
# 镜像
# frame1 = frame1[::-1, :, :]
# frame1 = frame1[:, ::-1, :]
frame_pip(frame1, frame2, N=81, w=0.6)
# 3. save the video via the writer
vid_writer.write(frame1)
cv2.imshow('camera', frame1)
# wait until key strokes to break
if cv2.waitKey(30) & 0xFF == ord('q'):
break
# 4. close the video handlers
vid_reader.release()
vid_capture.release()
vid_writer.release()
注:可能存在的问题以及解决办法(感谢李俊杰同学)
Problem 1:同时打开视频和摄像头的时候,一开始我是用vid_readerc = cv2.VideoCapture(0)来打开摄像头,但这时报warming:[ WARN:1] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (674) SourceReaderCB::~SourceReaderCB terminating async callback
Selution 1:上网搜索,也没有明确的介绍,有的说跟size有关,有的说是和版本有关系,但是改成vid_readerc = cv2.VideoCapture(0,cv2.CAP_DSHOW)就解决了,大概意思就是说:cv2.CAP_DSHOW是作为open调用的一部分传递标志。
Problem 2 :framec = cv2.resize(framec, (100, 100))
frames = cv2.resize(frames, (640, 480))
frames[20:120, -120:-20, :] = framec
这里的(framec, (100, 100),(frames, (640, 480)
frame后第一个表示行,第二个表示列,
但frames[20:120, -120:-20, :] = framec 第一个逗号前表示列,第二个表示 行。
Selution 2:取反即可
########## 返回目录 - 信息隐藏技术(Python) ###