Невозможно обрезать и сохранить ROI / ограничивающую рамку в opencv python

#python #opencv

#python #opencv

Вопрос:

Я пытаюсь сохранить только прямоугольную область ROI из видеофайла в изображения. Но все изображение сохраняется с КРАСНОЙ прямоугольной рамкой ROI. Что я здесь делаю не так? Я попытался сохранить rect_img, но это выдает ошибку «!_img.empty() в функции ‘imwrite'» и вообще не сохраняет никаких изображений.

Координаты upper_left и bottom_right предназначены для видео 1920 X 1080p, вам нужно будет настроить в соответствии с вашим разрешением видео.

 import cv2
from matplotlib import pyplot as plt
import imutils
import numpy as np
import pytesseract
  
cam_capture = cv2.VideoCapture('1080_EDIT.webm')

upper_left = (1400, 700)
bottom_right = (700, 1000)
ctr=1 #filename counter

while True:
    _, image_frame = cam_capture.read()
    ctr =1
    #Rectangle marker
    r = cv2.rectangle(image_frame, upper_left, bottom_right, (100, 50, 200), 5)
    rect_img = image_frame[upper_left[1] : bottom_right[1], upper_left[0] : bottom_right[0]]
    cv2.imwrite("rect" str(ctr) ".jpg",r)
    #print (rect_img)
    #img=cv2.imread(rect_img)
    gray = cv2.cvtColor(r, cv2.COLOR_BGR2GRAY) 
    gray = cv2.bilateralFilter(gray, 13, 15, 15) 

    edged = cv2.Canny(gray, 30, 200) 
    contours = cv2.findContours(edged.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    contours = imutils.grab_contours(contours)
    contours = sorted(contours, key = cv2.contourArea, reverse = True)[:10]
    screenCnt = None 
    
    for c in contours:
    
        peri = cv2.arcLength(c, True)
        approx = cv2.approxPolyDP(c, 0.018 * peri, True)
 
        if len(approx) == 4:
            screenCnt = approx
            break

    if screenCnt is None:
        detected = 0
        print ("No contour detected")
    else:
        detected = 1

    if detected == 1:
        cv2.drawContours(r, [screenCnt], -1, (0, 0, 255), 3)

    cv2.imshow("image", image_frame) 
    if cv2.waitKey(1) % 256 == 27 :
        break

cam_capture.release()
cv2.destroyAllWindows()
 
 

Ответ №1:

Решил это с помощью

 roi=r[700:1000,700:1400]
cv2.imwrite("rect" str(ctr) ".jpg",roi)