Anita Shukla
Anita Shukla

Reputation: 11

Unable to clip and save the ROI/bounding box in opencv python

Im trying to save only the rectangular ROI region from a video file into images. But the entire image is getting saved with the RED rectangular ROI box on it. What am I doing wrong here ? I tried saving rect_img but thats giving error "!_img.empty() in function 'imwrite'" , and not saving any images at all.

The upper_left and bottom_right coordinates are for a 1920 X 1080p video, you wil have to adjust is as per your video resolution.

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()
 

Upvotes: 0

Views: 233

Answers (1)

Anita Shukla
Anita Shukla

Reputation: 11

Solved it by

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

Upvotes: 0

Related Questions