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

时间:2018-12-13 03:55:37

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

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

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

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

  

错误:OpenCV(3.4.4)   C:\ projects \ opencv-python \ opencv \ modules \ imgproc \ src \ thresh.cpp:1524:   错误:(-215:声明失败)src.type()== CV_8UC1在函数中   '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

1 个答案:

答案 0 :(得分: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