openCV的安裝可以參照我的其他文章:
圖像的基本操作:
import cv2 import numpy as np filedir = "./AI/photo" #設置自己的lying file = "\zhangOne.jpg" #圖像的讀取 #img = cv2.imread("C:\\Users\chinaone\Desktop\AI\photo\zhangOne.jpg") img = cv2.imread(filedir+file) #圖像的顯示 cv2.namedWindow("Image") cv2.imshow("Image", img) cv2.waitKey (0) cv2.destroyAllWindows() imgX = cv2.imread(filedir + file,cv2.IMREAD_COLOR) #圖像的顯示:值爲 1,默認值,讀取彩色圖像,透明度會被忽略 imgY = cv2.imread(filedir + file,cv2.IMREAD_GRAYSCALE) #圖像的顯示:值爲 0,灰度模式讀取 cv2.imshow("imgX", imgX) cv2.imshow("imgY", imgY) cv2.waitKey (0) cv2.destroyAllWindows() #圖像的複製 empImg1 = np.zeros(img.shape,np.uint8) empImg2 = img.copy() empIma3=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) cv2.namedWindow("Image",cv2.WINDOW_NORMAL) cv2.imshow("Image", empIma3) cv2.waitKey (0) cv2.destroyAllWindows()
視頻的基本操作:
第一步:基本文件夾和庫設置
import cv2 import os filedir = os.getcwd() + '\data' file = "\out" print(filedir) fileidx = 0 exjpg = ".jpg" exavi = ".avi" exmp4 = ".mp4"
第二步:採集視頻保存某幾個圖像
def savePhoto(): print('savePhoto') fileidx = 0 cap = cv2.VideoCapture(0) #找到自己攝像頭的對應編號 while (cap.isOpened()): ref, vshow = cap.read() cv2.imshow("Video", vshow) fileidx += 1 stridx = str(fileidx) filename = filedir + file + stridx + exjpg if (fileidx % 20 == 0): cv2.imwrite(filename, vshow) print(fileidx) print(vshow) if cv2.waitKey(10) & 0xff == ord('q'): cv2.imwrite(filename, vshow) break cap.release() cv2.destroyAllWindows()
第三部:採集視頻保存成自己需要的格式
def saveVideo(): print('saveVideo') cap = cv2.VideoCapture(0) filename = filedir + file + '0' + exmp4 #out = cv2.VideoWriter(filename,cv2.CV_FOURCC('M','J','P','G'), 10,(640,480)) out = cv2.VideoWriter(filename,cv2.CV_FOURCC('M','J','P','G'), 10,(640,480)) while True: ret, frame = cap.read() if ret == True: frame = cv2.flip(frame, 1) a = out.write(frame) cv2.imshow("frame", frame) if cv2.waitKey(1) & 0xFF == ord('q'): break else: break cap.release() out.release() cv2.destroyAllWindows()
最後調用執行:
if __name__ == '__main__': savePhoto() #saveVideo()