Python cv2框选视频保存图片

cv2框选视频保存图片

一、任务描述

从一段视频中选出某一区域,摁s保存该区域图片

二、代码

videoName = r'浙江卫视:十二道锋味.mp4'
saveDir = './data/train/Zhejiang/'

import cv2

n = 0  # number of saved pictures
rectangle = []  # points of crop area


def onTrackbarSlide(pos):
    videoCapture.set(cv2.CAP_PROP_POS_MSEC, pos * 1000)


def onmouse(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONDOWN:
        rectangle.append((x, y))
        if len(rectangle) > 2:
            rectangle.clear()
            cv2.destroyWindow('crop')


if __name__ == '__main__':
    cv2.namedWindow('winname')
    videoCapture = cv2.VideoCapture(videoName)

    FPS = videoCapture.get(cv2.CAP_PROP_FPS)
    frameCount = videoCapture.get(cv2.CAP_PROP_FRAME_COUNT)
    timeCount = int(frameCount / FPS)

    cv2.createTrackbar('Position', 'winname', 0, timeCount, onTrackbarSlide)
    cv2.setMouseCallback('winname', onmouse)

    while True:
        ret, frame = videoCapture.read()
        if ret is True:
            crop = frame
            if len(rectangle) == 2:
                crop = frame[rectangle[0][1]:rectangle[1][1], rectangle[0][0]:rectangle[1][0]]
                # cv2.rectangle(frame, rectangle[0], rectangle[1], (0, 0, 255), 2)#draw rectangle
                cv2.imshow('crop', crop)
            cv2.imshow('winname', frame)

            current = int(videoCapture.get(cv2.CAP_PROP_POS_MSEC) / 1000)
            cv2.setTrackbarPos('Position', 'winname', current)  # renew the location of video

            key = cv2.waitKey(25)
            if key & 0xFF == ord('q'):  # quit
                break
            elif key & 0xFF == ord('s'):  # save
                cv2.imwrite(saveDir + str(n) + '.jpg', crop)
                n += 1
                print('Saved {} pictures'.format(n))
        else:
            break

    videoCapture.release()
    cv2.destroyAllWindows()

三、结果

在这里插入图片描述

发布了223 篇原创文章 · 获赞 63 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/lly1122334/article/details/89933268