1. 程式人生 > >OpenCV處理檔案、視訊和攝像頭

OpenCV處理檔案、視訊和攝像頭

影象的本質(影象可以用陣列來表示)

import numpy as np
import cv2

img = np.zeros((3, 3), dtype=np.uint8)
print(img, img.dtype)

img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
print(img, img.dtype, img.shape)

圖片格式轉換(jpg->png)

image = cv2.imread("img/1.jpg")
cv2.imwrite("img/1.png",image)

使用numpy.array訪問影象資料

image = cv2.imread("img/1.jpg")
image[0:100,0:100] = [255,255,255]
cv2.imshow("Demo",image)
cv2.waitKey(0)

影象的屬性

image = cv2.imread("img/1.jpg")
print(image.shape)
print(image.size)
print(image.dtype)

shape:影象的寬度、高度和通道數

size:影象的大小=寬*高*通道數

dtype:影象畫素值的資料型別

視訊型別轉換

import numpy as np
import cv2 videoCapture = cv2.VideoCapture("img/小杰克的攻擊.mp4") fps = videoCapture.get(cv2.CAP_PROP_FPS) # 獲取每秒多少幀 size = ( int(videoCapture.get(cv2.CAP_PROP_FRAME_WIDTH)), # 獲取視訊幀寬度 int(videoCapture.get(cv2.CAP_PROP_FRAME_HEIGHT)) # 獲取視訊幀高度 ) videoWriter = cv2.VideoWriter("output.avi
", cv2.VideoWriter_fourcc('I', '4', '2', '0'), fps, size) success ,frame = videoCapture.read() while success: videoWriter.write(frame) success,frame = videoCapture.read()