万花筒影片效果
这篇教学会使用 OpenCV 里翻转影片和改变尺寸的功能,实作出一个有趣的万花筒影片效果。
因为程序中的 OpenCV 会需要使用镜头或 GPU,所以请使用本机环境 ( 参考:使用 Python 虚拟环境 ) 或使用 Anaconda Jupyter 进行实作 ( 参考:使用 Anaconda ) ,并安装 OpenCV 函数库 ( 参考:OpenCV 函数库 )。
镜像合成图像
使用 NumPy 产生全黑背景后,读取摄影镜头的图像并改变图像尺寸,裁切出黑色背景一半尺寸的图像,将图像放在全黑背景的左边,接着使用 flip 方法将这一半的图像水平翻转,放在全黑背景的右边,就实现了镜像合成的效果。
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
output = np.zeros((360,640,3), dtype='uint8') # 產生 640x360 的黑色背景
if not cap.isOpened():
print("Cannot open camera")
exit()
while True:
ret, img = cap.read()
img = cv2.resize(img, (640, 360)) # 改變影像尺寸為 640x360
img = img[:360, :320] # 取出 320x360 的影像
img2 = cv2.flip(img, 1) # 左右翻轉影像
output[:, :320] = img # 將 output 左邊內容換成 img
output[:, 320:640] = img2 # 將 output 右邊內容換成 img2
cv2.imshow('oxxostudio', output)
if cv2.waitKey(50) == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
四格万花筒效果
延伸上方的程序码,将背景尺寸改成 640x640,并将读取的图像改成上下左右四格,就能做出四格万花筒的效果。
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
output = np.zeros((640,640,3), dtype='uint8')
if not cap.isOpened():
print("Cannot open camera")
exit()
while True:
ret, img = cap.read()
img = cv2.resize(img,(640, 360))
img = img[:320, :320] # 取出 320x320 的區域
img2 = cv2.flip(img, 1) # 左右翻轉
img3 = cv2.flip(img, 0) # 上下翻轉
img4 = cv2.flip(img, -1) # 上下左右翻轉
output[:320, :320] = img # 左上
output[:320, 320:640] = img2 # 右上
output[320:640, :320] = img3 # 左下
output[320:640, 320:640] = img4 # 右下
cv2.imshow('oxxostudio', output)
if cv2.waitKey(50) == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
微信扫码关注
抖音扫码关注