【问题标题】:Getting TypeError: Expected cv::UMat for argument 'src' while casting bgr to rgb获取 TypeError:将 bgr 转换为 rgb 时参数“src”的预期 cv::UMat
【发布时间】:2019-12-05 13:13:42
【问题描述】:

我想将 bgr 转换为 rgb,但出现“TypeError: Expected cv::UMat for argument 'src'”错误

pip freeze:

greenlet==0.4.15
msgpack==0.6.1
mss==4.0.3
numpy==1.17.0
opencv-python==4.1.0.25
Pillow==6.1.0
pywin32==224

import numpy as np
import cv2
from mss import mss
from PIL import Image
from win32api import GetSystemMetrics

sct = mss()

(w, h) = (GetSystemMetrics(0) // 2, GetSystemMetrics(1) * 2 // 3)
(margin_l, margin_t) = (GetSystemMetrics(0) // 4, GetSystemMetrics(1)
                        // 3)

while True:
    monitor = {
        'top': margin_t,
        'left': margin_l,
        'width': w,
        'height': h,
    }
    img = Image.frombytes('RGB', (w, h), sct.grab(monitor).rgb)

    # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

    cv2.imshow('DEBUG', np.array(img))
    if cv2.waitKey(25) & 0xFF == ord('q'):
        cv2.destroyAllWindows()
        break

img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 不能改变“颜色空间”,但是没有这个字符串,代码可以正常工作,但是所有的红色都是蓝色的。

【问题讨论】:

标签: python python-3.x numpy opencv python-mss


【解决方案1】:

在下方使用正确颜色捕获屏幕的更好方法

# -*- coding: utf-8 -*-
import numpy as np
from PIL import ImageGrab
import cv2
from win32api import GetSystemMetrics

bbox = (GetSystemMetrics(0)//5, GetSystemMetrics(1)//3, GetSystemMetrics(0)//1.3, GetSystemMetrics(1))

while(True):
    printscreen = np.array(ImageGrab.grab(bbox=bbox))
    printscreen = cv2.cvtColor(printscreen, cv2.COLOR_BGR2RGB)
    cv2.imshow('window', printscreen)
    if cv2.waitKey(25) & 0xFF == ord('q'):
        cv2.destroyAllWindows()
        break

【讨论】:

    【解决方案2】:

    此代码适用于我,需要调整:

    • monitor 定义移出while 之外。
    • 为 MSS 使用了 with 上下文管理器。
    • 删除了 PIL 的使用(它会减慢整个过程)。
    • 删除了对img.rgb 的访问(这会减慢整个过程)。
    monitor = {
        'top': margin_t,
        'left': margin_l,
        'width': w,
        'height': h,
    }
    
    with mss() as sct:
        while True:
            # Grab it
            img = np.array(sct.grab(monitor))
    
            # Convert from BGRA to RGB
            img = cv2.cvtColor(img, cv2.COLOR_BGRA2RGB)
    
            # Display
            cv2.imshow('DEBUG', img)
            if cv2.waitKey(25) & 0xFF == ord('q'):
                cv2.destroyAllWindows()
                break
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-18
      • 1970-01-01
      • 2020-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多