0

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

我收到以下错误消息。我已经尝试将其转换为grayscale但似乎不起作用,并且我已经尝试过numpy.ndarray.flatten (1 dimension),它可以正常工作但无法正确显示。

我最终得到一个长长的灰色条。我不确定我还应该做什么。任何帮助表示赞赏。

错误:OpenCV(3.4.4) C:\projects\opencv-python\opencv\modules\imgproc\src\thresh.cpp:1524: 错误: (-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
4

1 回答 1

0

更改您的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
于 2018-12-16T13:05:28.873 回答