Ошибка подачи массива numpy d.type uint8 в адаптивную пороговую функцию - PullRequest
0 голосов
/ 13 декабря 2018

Я пытаюсь передать массив numpy в функцию Process_img (adaptivethreshold).Массив numpy имеет тип данных uint8 и 3 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 голосов
/ 16 декабря 2018

Измените функцию 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
...