如何使用 OpenCV 从视频中读取灰度 img?

How to read grayscale img from a video with OpenCV?

我从我的 pic 目录中读取所有图片,然后在将它们全部写入视频之前使用 canny 边缘检测将它们每张转换为灰度。

但是,当我用我的视频软件播放它时,它显示绿色背景,而且我无法从中读取视频帧。有人可以告诉我如何解决吗?

示例代码

import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt

fourcc = cv.VideoWriter_fourcc(*"I420")
out = cv.VideoWriter("t2.avi", fourcc, 1, (640, 480), 0)
for pic in glob.glob1("./pic/", "A*"):
    img = cv.imread(f"./pic/{pic}", -1)
    
    edge = cv.Canny(img, 100, 200)
    edge = cv.resize(edge, (640, 480))
    out.write(edge)

out.release()

# Cant read video frame here:
cap = cv.VideoCapture("t2.avi")
ret, frame = cap.read()
if ret:
    plt.imshow(frame)
else:
    print("end")
    cap.release()

视频以绿色背景播放

看起来 I420 FOURCC 和灰度格式之间存在兼容性问题。

fourcc = cv.VideoWriter_fourcc(*"I420") 替换为:

fourcc = cv.VideoWriter_fourcc(*"GREY")

注:

  • 我在 Windows 10 中使用 OpenCV 4.5.5,它与 "GREY".
    一起工作 我不确定它是否适用于所有平台和版本。

I420 应用彩色视频。
您可以将 I420 与彩色视频一起使用:

out = cv.VideoWriter("t2.avi", fourcc, 1, (640, 480), 0)替换为:

out = cv.VideoWriter("t2.avi", fourcc, 1, (640, 480), 1)

写入前将edge转换为BGR:

edge = cv.cvtColor(edge, cv.COLOR_GRAY2BGR)
out.write(edge)

使用 "GREY" FOURCC 的代码示例:

import numpy as np
import cv2 as cv
#import matplotlib.pyplot as plt
import glob

#fourcc = cv.VideoWriter_fourcc(*"I420")
fourcc = cv.VideoWriter_fourcc(*"GREY")
out = cv.VideoWriter("t2.avi", fourcc, 1, (640, 480), 0)
for pic in glob.glob1("./pic/", "A*"):
    img = cv.imread(f"./pic/{pic}", -1)
    
    edge = cv.Canny(img, 100, 200)
    edge = cv.resize(edge, (640, 480))
    out.write(edge)

out.release()

# Cant read video frame here:
cap = cv.VideoCapture("t2.avi")

while True:
    ret, frame = cap.read()
    if ret:
        #plt.imshow(frame)
        cv.imshow('frame', frame)
        cv.waitKey(1000)
    else:
        print("end")
        cap.release()
        break

cv.destroyAllWindows()