首页 > 解决方案 > cv2.cvtColor(img,cv2.COLOR_BGR2RGB) 不工作

问题描述

我正在尝试在 python 中使用 mss 和 Opencv 创建屏幕录像机,我正在捕获的视频的颜色与原始计算机屏幕的颜色非常不同。我试图在网上找到解决方案,每个人都说应该使用 cvtColor() 修复它,但我的代码中已经有了它。

import cv2
from PIL import Image
import numpy as np
from mss import mss
import threading
from datetime import datetime

`

def thread_recording():

    fourcc=cv2.VideoWriter_fourcc(*'mp4v')
    #fourcc=cv2.VideoWriter_fourcc(*'XVID')
    out=cv2.VideoWriter(vid_file,fourcc,50,(width,height))
    mon = {"top": 0, "left": 0, "width":width, "height":height}
    sct = mss()

    thread1=threading.Thread(target=record,args=(mon,out,sct))
    thread1.start()

def record(mon,out,sct):

    global recording
    recording=True

    while recording:
        frame= np.array(sct.grab(mon))
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        out.write(frame)

    out.release()

vid_file 变量包含一串带有 mp4 扩展名的输出文件名

我的屏幕截图

录制视频的屏幕截图

标签: python-3.xopencvpython-mss

解决方案


所以,我环顾四周,发现这显然是 wards 上 3.x 版本的 opencv 中的一个错误。然后我尝试 PIL 获取 rgb 图像并删除 cvtColor(),但它产生了一个空视频。我删除了两个 cvtColor () 以及@ZdaR 建议的 PIL Image 它再次写了空视频因此我不得不把它放回去并繁荣。即使 cvtColor() 似乎什么都不做,由于某种未知的原因,它必须存在。当您将 PIL Image 与 cvtColor() 一起使用时,它会按预期写入视频

from PIL import Image
def record(mon,out,sct):

    global recording
    recording=True

    while recording:
        frame=sct.grab(mon)
        frame = Image.frombytes('RGB', frame.size, frame.rgb)
        frame = cv2.cvtColor(np.array(frame), cv2.COLOR_BGR2RGB)
        out.write(np.array(frame))

    out.release()

因为我对编程很陌生,如果我错过或忽略了一些重要的事情,我将非常感谢您的帮助


推荐阅读