Как сделать прямоугольник видимым при выделении области на изображении? - PullRequest
0 голосов
/ 07 февраля 2020

Следующий код работает нормально и распознает выбранную часть изображения. Прямоугольник для выбора области виден после EVENT_LBUTTONUP, а не во время выделения. Таким образом, иногда выделяется дополнительная область.

Есть ли решение сделать прямоугольник видимым при выборе области? .. Пробовал различные комбинации событий, таких как LBUTTONDOWN или MOUSEMOVE ... Это должна быть одна из этих комбинаций.

import cv2
import pytesseract

IMAGE_FILE_LOCATION = "0025.jpg"              # PhotoCopy :P
image = cv2.imread(IMAGE_FILE_LOCATION)         # image read
coordinates = []

# Defining the event listener (callback function)
def shape_selection(event, x, y, flags, param):
    # making coordinates global
    global coordinates

    # Storing the (x1,y1) coordinates when left mouse button is pressed
    if event == cv2.EVENT_LBUTTONDOWN:
        coordinates = [(x, y)]

        # Storing the (x2,y2) coordinates when the left mouse button is released and make a rectangle on the selected region
    elif event == cv2.EVENT_LBUTTONUP:
        coordinates.append((x, y))

        # Drawing a rectangle around the region of interest (roi)
        cv2.rectangle(image, coordinates[0], coordinates[1], (0, 0, 255), 1)
        cv2.imshow("image", image)

image_copy = image.copy()
cv2.namedWindow("image")
cv2.setMouseCallback("image", shape_selection)

# keep looping until the 'q' key is pressed
while True:
    # display the image and wait for a keypress
    cv2.imshow("image", image)
    key = cv2.waitKey(1) & 0xFF

    if key == 13:  # If 'enter' is pressed, apply OCR
        break

    if key == 27:  # Clear the selection when 'Esc' is pressed
        image = image_copy.copy()

if len(coordinates) == 2:
    image_roi = image_copy[coordinates[0][1]:coordinates[1][1],
                coordinates[0][0]:coordinates[1][0]]
    cv2.imshow("Selected Region of Interest - Press any key to proceed", image_roi)
    cv2.waitKey(0)

# closing all open windows
cv2.destroyAllWindows()
text = pytesseract.image_to_string(image_roi)
print("The text in the selected region is as follows:")
print(text)

1 Ответ

0 голосов
/ 11 февраля 2020

Этот код может отображать прямоугольник, пока второй щелчок не выполняется.

def shape_selection(event, x, y, flags, param):
    global coordinates
    if event == cv2.EVENT_LBUTTONDOWN:
        coordinates = [(x, y)]
        coordinates.append((x,y))
    elif event == cv2.EVENT_MOUSEMOVE:
        if len(coordinates) == 2:
            coordinates.pop(1)
            coordinates.append((x,y))
    elif event == cv2.EVENT_LBUTTONUP:
        coordinates.pop(1)
        coordinates.append((x,y))
    if len(coordinates) == 2:
        image[:] = image_copy[:]
        cv2.rectangle(image, coordinates[0], coordinates[1], (0, 0, 255), 1)
        cv2.imshow("image", image)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...