正文
filename: A string representing the file name. The filename must include image format like .jpg, .png, etc.
image: It
is
the image that
is
to be saved.
Example
cv2.imwrite(
'images/img'
,img)
读取视频并与网络摄像头集成
读取视频文件与在OpenCV中读取图像文件非常相似,区别在于我们使用了cv2.videocapture。
video = cv2.VideoCapture("FILEPATH.mp4")
Example
video = cv2.VideoCapture("video/dog/dog.mp4")
视频是许多帧结合在一起的集合,每帧都是一幅图像。要使用OpenCV观看视频,我们只需要使用while循环显示视频的每一帧。
while True:
success , img = cap.read()
cv2.imshow("Video",img)
if cv2.waitKey(1) & 0xff==ord('q'):##key 'q' will break the loop
break
要与网络摄像头集成,我们需要传递网络摄像头的端口值而不是视频路径。如果你使用的是笔记本电脑,但没有连接任何外部网络摄像头,则只需传递参数0;如果你有外部网络摄像头,则传递参数1。
cap = cv2.VideoCapture(0)
cap.set(3,640) ## Frame width
cap.set(4,480) ## Frame Height
cap.set(10,100) ## Brightness
while True:
success, img = cap.read()
cv2.imshow("Video",img)
if cv2.waitKey(1) & 0xff == ord('q'):
break
调整大小和裁剪图像
调整大小是更改图像形状的过程。在Opencv中,我们可以使用resize函数调整图像形状的大小。
cv2.resize(IMG,(WIDTH,HEIGHT))
IMG: image which we want to resize
WIDTH: new width of the resize image
HEIGHT: new height of the resize image
Example
cv2.resize(img,(224,224))
要首先调整图像的大小,我们需要知道图像的形状。我们可以使用
shape
来找到任何图像的形状,然后根据图像形状,可以增加或减小图像的大小。让我们看看示例。
import cv2
img = cv2.imread("images/img0.jpg") ##Choose any image
print(img.shape)
imgResize = cv2.resize(img,(224,224)) ##Decrease size
imgResize2 = cv2.resize(img,(1024,1024)) ##Increase size
cv2.imshow("Image",img)
cv2.imshow("Image Resize",imgResize)
cv2.imshow("Image Increase size",imgResize2)
print(imgResize.shape)
cv2.waitKey(0)
如果你不想对宽度和高度进行硬编码,也可以使用形状,然后使用索引来增加宽度和高度。
import cv2
img = cv2.imread("images/img0.jpg") ##Choose any image
print(img.shape)
shape = img.shape
imgResize = cv2.resize(img,(shape[0]//2,shape[1]//2))##Decrease size
imgResize2 = cv2.resize(img,(shape[0]*2,shape[