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()