用视频做检测需要把每一帧resize成检测器需要的大小。这里是把4196×2160(w×h)大小的视频缩放成1024×1024。为了不引起形状变化,按比例resize成1941×1024,之后裁剪。
import cv2
def img_resize(image):
height, width = image.shape[0], image.shape[1]# 2160,4196
width_new = 1024
height_new = 1024
# 2160/1024 < 4196/1024
if width / height <= width_new / height_new:
img_new = cv2.resize(image, (width_new, int(height * width_new / width)))
else:# w/w_new >= h/h_new, 按照h比例缩放,w_current = w * (h_new/h)
img_new = cv2.resize(image, (int(width * height_new / height), height_new))
return img_new
videowriter = cv2.VideoWriter("/home/chenlc/am/demo/DJI_0008_resize"+".avi", cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), 50, (1941,1024)) # 50 帧率。“.mov”会报错,改成‘.avi’了。
cap = cv2.VideoCapture("/home/chenlc/am/demo/DJI_0008.MP4")
success, _ = cap.read()
i = 0
while success:
success, img1 = cap.read()
if i%50 ==0:
print(i/50)//输出写了多少帧了
i=i+1
try:
img = img_resize(img1)
videowriter.write(img)
except:
break