pythonpython-3.xnumpyopencvpython-mss

Getting TypeError: Expected cv::UMat for argument 'src' while casting bgr to rgb


I wanna cast bgr to rgb, but I'm getting "TypeError: Expected cv::UMat for argument 'src'" error

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) doesn't work to change "colorspace", but without this string, code works just fine, but all reds are blue.


Solution

  • Better way to capture screen with correct colors below

    # -*- 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