将 numpy 数组 d.type uint8 送入自适应阈值函数时出错

Error feeding numpy array d.type uint8 into adaptivethreshold function

我正在尝试将一个 numpy 数组输入到 Process_img (adaptivethreshold) 函数中。 numpy 数组的数据类型为 uint83 dimensions,该函数应接受该数据类型。

我收到以下错误消息。我试过将它转换为 grayscale,但似乎没有用,我试过 numpy.ndarray.flatten (1 dimension),它可以正常工作,但不能正确显示。

我最后得到一个长长的灰色条。我不确定我还应该做什么。感谢任何帮助。

error: OpenCV(3.4.4) C:\projects\opencv-python\opencv\modules\imgproc\src\thresh.cpp:1524: error: (-215:Assertion failed) src.type() == CV_8UC1 in function 'cv::adaptiveThreshold'

import time
import cv2
import mss
import numpy

# Attempts to change the image to black and white relative to a general area
def process_img(image):
    processed_img = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,2)
    return processed_img

while (True):
    last_time = time.time()

    # Takes a snapshot of the screen location
    with mss.mss() as sct:
        monitor = {"top": 40, "left": 0, "width": 960, "height": 540}  

    # Converts the snapshot to a numpy array    
        npm = numpy.array(sct.grab(monitor))

    # Checks the data type of the numpy array
    print (npm.dtype)

    # Feeds the numpy array into the "process_img" function
    new_screen = process_img(npm)

    # Displays the processed image
    cv2.imshow('Window',new_screen)                  

    #This keeps the screen displayed over time instead of flickering 1ms basically the screen's refresh rate
    if cv2.waitKey(1) & 0xFF == ord('q'):           
        cv2.destroyAllWindows()
        break

更改 process_img() 函数以将图像转换为灰度:

def process_img(image):
    image = cv2.cvtColor(image, cv2.COLOR_BGRA2GRAY)
    return cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,2)

此外,您应该将 with mss.mss() as sct: 移到 while 之外以保持性能:

import time

import cv2
import mss
import numpy


# Attempts to change the image to black and white relative to a general area
def process_img(image):
    image = cv2.cvtColor(image, cv2.COLOR_BGRA2GRAY)
    return cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,2)


with mss.mss() as sct:
    # Takes a snapshot of the screen location
    monitor = {"top": 40, "left": 0, "width": 960, "height": 540}

    while True:
        last_time = time.time()

        # Converts the snapshot to a numpy array
        npm = numpy.array(sct.grab(monitor))

        # Checks the data type of the numpy array
        print(npm.dtype)

        # Feeds the numpy array into the "process_img" function
        new_screen = process_img(npm)

        # Displays the processed image
        cv2.imshow("Window", new_screen)

        # This keeps the screen displayed over time instead of flickering 1ms basically the screen's refresh rate
        if cv2.waitKey(1) & 0xFF == ord("q"):
            cv2.destroyAllWindows()
            break