您的位置:首页 > 运维架构

opencv读取图片、视频、摄像头

2018-01-22 13:14 786 查看
计算机视觉处理,少不了需要会opencv,所以下面练习一下。

# -*- coding: utf-8 -*-
"""
Created on Mon Jan 22 10:38:23 2018

"""

import numpy as np
import cv2
from matplotlib import pyplot as plt

#opencv 读图
img = cv2.imread("E:\\python\\opencv\\images\\demo0.png")

#显示图片
'''
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
'''

#可以调整窗口大小
'''
cv2.namedWindow('image', cv2.WINDOW_NORMAL)
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
'''

#保存图片
'''
cv.imwrite('messigray.png',img)
'''

#显示图片,,按下’s’键保存后退出,或者按下ESC 键退出不保存。
#:如果你用的是64 位系统,你需要将 k = cv2.waitKey(0) 这行改成k = cv2.waitKey(0)&0xFF。
'''
cv.imshow('image',img)
k = cv.waitKey(0)
if k == 27: # wait for ESC key to exit
cv.destroyAllWindows()
elif k == ord('s'): # wait for 's' key to save and exit
cv.imwrite('messigray.png',img)
cv.destroyAllWindows()
'''

#用matplotlib
'''
plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis
plt.show()
'''

#用摄像头读数据
#为了获取视频,你应该创建一个VideoCapture 对象。他的参数可以是设备的索引号,或者是一个视频文件。设备索引号就是在指定要使用的摄像头。
#一般的笔记本电脑都有内置摄像头。所以参数就是0。你可以通过设置成1 或者其他的来选择别的摄像头。之后,你就可以一帧一帧的捕获视频了。但是最后,别忘了停止捕获视频。
#保存成图片
'''
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
#print ret
#print frame
# Our operations on the frame come here
#gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #COLOR_BGR2HSV COLOR_BGR2GRAY
# Display the resulting frame
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
img = cv2.imwrite("E:\\python\\opencv\\image\\demo.png",frame)
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
'''

#把摄像头读取成视频
'''
cap = cv2.VideoCapture(0)
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc("D", "I", "B", " ") #*'XVID'由于编码不能用
out = cv2.VideoWriter('E:\\python\\opencv\\image\\output.avi',fourcc, 20.0, (640,480))
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
frame = cv2.flip(frame,0)
print frame
# write the flipped frame
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
'''

#opencv读取视频
'''
cap = cv2.VideoCapture("E:\\python\\opencv\\image\\output.avi")
print cap.isOpened()
while(cap.isOpened()):
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
print gray
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
'''
参考:https://docs.opencv.org/3.4.0/dc/d4d/tutorial_py_table_of_contents_gui.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: