无法将视频转换为灰度

时间:2019-03-28 09:31:29

标签: python opencv video-processing

我正在尝试将相机Feed中的视频(低fps)转换为灰色。我现在已经成功获取了视频,我想将其转换为灰度。

我已经尝试过基本的opencv操作,但是它不起作用。打开视频时,我得到一个视频文件。

import cv2
import time

cap = cv2.VideoCapture('output.avi')
fourcc = cv2.VideoWriter_fourcc(*'XVID')
print(fourcc)
out = cv2.VideoWriter('grey.avi',fourcc, 30.0, (800,600))
while True:    
    ret, frame = cap.read()
    time.sleep(0.1)
    cv2.imshow('frame1',frame)
    frame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
    out.write(frame)
    cv2.imwrite('img.jpg',frame)
    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()
out.release()
cv2.destroyAllWindows()

1 个答案:

答案 0 :(得分:1)

您需要更改isColor中的cv2.VideoWriter标志。当前,视频编写器设置设置为彩色而不是灰度。您错误地尝试将3通道彩色图像(OpenCV的默认值为BGR)另存为灰度图像。

更改

out = cv2.VideoWriter('grey.avi',fourcc, 30.0, (800,600))

out = cv2.VideoWriter('grey.avi',fourcc, 30.0, (800,600), isColor=False)

您的总体目标似乎也是从流/摄像机供稿捕获视频并将捕获的视频保存为灰度格式。这是一个“多合一”小部件,可从摄像机流链接(RTSP)读取帧,将每个帧转换为灰度,然后将其保存为视频。将video_src更改为相机流链接。

RTSP video stream to grayscale video

from threading import Thread
import cv2

class VideoToGrayscaleWidget(object):
    def __init__(self, src=0):
        # Create a VideoCapture object
        self.capture = cv2.VideoCapture(src)

        # Default resolutions of the frame are obtained (system dependent)
        self.frame_width = int(self.capture.get(3))
        self.frame_height = int(self.capture.get(4))

        # Set up codec and output video settings
        self.codec = cv2.VideoWriter_fourcc('X','V','I','D')
        self.output_video = cv2.VideoWriter('output.avi', self.codec, 30, (self.frame_width, self.frame_height), isColor=False)

        # Start the thread to read frames from the video stream
        self.thread = Thread(target=self.update, args=())
        self.thread.daemon = True
        self.thread.start()

    def update(self):
        # Read the next frame from the stream in a different thread
        while True:
            if self.capture.isOpened():
                (self.status, self.frame) = self.capture.read()

    def show_frame(self):
        # Convert to grayscale and display frames
        if self.status:
            self.gray = cv2.cvtColor(self.frame, cv2.COLOR_BGR2GRAY)
            cv2.imshow('grayscale frame', self.gray)

        # Press 'q' on keyboard to stop recording
        key = cv2.waitKey(1)
        if key == ord('q'):
            self.capture.release()
            self.output_video.release()
            cv2.destroyAllWindows()
            exit(1)

    def save_frame(self):
        # Save grayscale frame into video output file
        self.output_video.write(self.gray)

if __name__ == '__main__':
    video_src = 'Your video stream link!'
    video_stream_widget = VideoToGrayscaleWidget(video_src)
    while True:
        try:
            video_stream_widget.show_frame()
            video_stream_widget.save_frame()
        except AttributeError:
            pass