常用的图像(视频)预处理操作

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.rotate(270)
    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)
# print(img_data)
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.merge([r, g, b])
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()
  • 0
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值