1、OpenCV 读取数据

OpenCV with Python

图片的读写

cv2.imread('picture_name.jpg')

默认返回BGR三色通道的图片,返回值类型为numpy.array
可以添加参数使图片改为灰度图

cv2.imread('picture_name.jpg', cv2.IMREAD_GRAYSCALE)

保存图片

cv2.imwrite('picture_name', img_array)

视频文件的读写

OpenCV的VideoCapture类和VideoWriter类都支持各种格式的视频文件。
首先创建VideoCapture对象

videoCapture = cv2.VideoCapture('video_name.type')

然后确定视频的帧率和尺寸

fps = videoCapture.get(cv2.CAP_PROP_FPS)
size = (int(videoCapture.get(CAP_PROP_FRAME_WIDTH)), int(videoCapture.get(CAP_PROP_FRAME_HEIGHT)))

视频读取循环:

success, frame = videoCapture.read()
while success:
	#operation
	success, frame = videoCapture.read()

建立写视频对象

videoWriter = cv2.VideoWriter('output_video_name.type', cv2.VideoWriter_fourcc('I','4','2','0'), fps, size)

其中第二个参数是编解码器代号

摄像头内容的捕获

首先创建VideoCapture对象,对于摄像头而言,通常是用设备索引来构建VideoCapture对象。

cameraCapture = cv2.VideoCapture(cam_index)

类似视频读取,确定fps和size

fps = 30 #估计值
size = (int(cameraCapture .get(CAP_PROP_FRAME_WIDTH)), int(cameraCapture .get(CAP_PROP_FRAME_HEIGHT)))

VideoCapture类的get()方法不能返回摄像头的帧率,它只返回0。
根据帧率确定读入的视频时长。

numFramesRemaining = 10 * fps #即采集10秒钟的视频

逐帧读取循环体

success, frame = cameraCapture.read()
while success and numFramesRemaining > 0
	# operation
	success, frame = cameraCapture.read()
	numFramesRemaining = numFramesRemaining - 1

读完之后要关闭摄像头

cameraCapture.release()

你可能感兴趣的:(图像处理,opencv,计算机视觉,python)