1. 读取视频并提取帧
import cv2
cameraCapture = cv2.VideoCapture('./VID_20200228_060756.mp4')
cv2.namedWindow('camera', cv2.WINDOW_NORMAL)
success, frame = cameraCapture.read()
n = 0
while success:
n+=1
if cv2.waitKey(1) == 27:
break
cv2.imshow('camera', frame)
success, frame = cameraCapture.read()
milliseconds = cameraCapture.get(cv2.CAP_PROP_POS_MSEC)
print(frame.shape)
seconds = milliseconds//1000
milliseconds = milliseconds%1000
minutes = 0
hours = 0
if seconds >= 60:
minutes = seconds//60
seconds = seconds % 60
if minutes >= 60:
hours = minutes//60
minutes = minutes % 60
print(int(hours), int(minutes), int(seconds), int(milliseconds))
if n%20==0:
frame_name = str(milliseconds)+".jpg"
cv2.imwrite(frame_name, frame)
cv2.destroyAllWindows()
cameraCapture.release()
2. 旋转和裁剪图片
from PIL import Image
import os
img_paths = os.listdir("./img_raw")
for img_path in img_paths:
print(img_path)
img = Image.open("./img_raw/"+img_path)
img_out = img.transpose(Image.ROTATE_270)
img_out = img_out.crop((0,0,1024,1024))
img_out.save(os.path.basename(img_path)+'.jpg')
3. PIL/numpy/cv2图片处理互转
3.1. 使用PIL打开图片,并转换为numpy数组
from PIL import Image
img = Image.open('cat.jpg')
img.show()
img_data = np.array(img)
h = img_data.shape[0]
w = img_data.shape[1]
print(img_data.shape)
for i in range(h):
for j in range(h):
img_data[i][j]=img_data[j][i]
img = Image.fromarray(img_data.astype('uint8')).convert('RGB')
img.show()
3.2. 使用cv2打开并显示图片
cv2_img = cv2.imread('cat.jpg')
print(cv2_img.shape)
cv2.imshow('RGB image', cv2_img)
if cv2.waitKey(0)&0xff == 'q':
cv2.destroyAllWindows(0)
cv2_img = cv2.cvtColor(cv2_img, cv2.COLOR_BGR2RGB)
print(cv2_img.shape)
cv2.imshow('RGB image', cv2_img)
if cv2.waitKey(0)&0xff == 'q':
cv2.destroyAllWindows(0)
3.3. 使用cv2拆分RGB通道,并用matplot显示
img_bgr = cv2.imread('cat.jpg')
b, g, r = cv2.split(cv2_img)
img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
cv2.rectangle()
img_array = np.array(img_rgb)
img_array = np.transpose(img_array, (1,0,2))
img_array[:, :, 0] = img_array[:, :, 2]
img_array[:, :, 1] = img_array[:, :, 2]
print(img_array.shape)
plt.subplot(221)
plt.imshow(img_bgr)
plt.subplot(222)
plt.imshow(img_rgb)
plt.subplot(223)
plt.imshow(img_array)
plt.show()