Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

saving contents of bounding box as a new image - opencv python

Tags:

python

opencv

I am trying to work with a code snippet that uses opencv to identify the largest contour/object within an image. The code below succesfully creates the bounding box, but what is the best way to save the bounding box as a seperate image, so I can store the largest object within an image as a new jpg file. Here is the code I am working with:

import numpy as np
import cv2

font = cv2.FONT_HERSHEY_SIMPLEX
lineType = cv2.LINE_AA

im = cv2.imread('test/originals/8.jpg')
im_ycrcb = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)

ball_ycrcb_mint = np.array([0, 90, 100],np.uint8)
ball_ycrcb_maxt = np.array([25, 255, 255],np.uint8)
ball_ycrcb = cv2.inRange(im_ycrcb, ball_ycrcb_mint, ball_ycrcb_maxt)
cv2.imwrite('test/outputs/output8.jpg', ball_ycrcb) # Second image
areaArray = []
count = 1

_, contours, _ = cv2.findContours(ball_ycrcb, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for i, c in enumerate(contours):
    area = cv2.contourArea(c)
    areaArray.append(area)
    areaLargest = np.argmax(areaArray)
    areaLargestMax = max(areaArray)
    areaLargestCnt = contours[areaLargest]
    x, y, w, h = cv2.boundingRect(areaLargestCnt)
    roi = im [y:y+h, x:x+w]
    cv2.imwrite('test/contours.jpg', im)   
    if area == areaLargestMax and area > 10000:
        cv2.drawContours(im, contours, i, (255, 0, 0), 7)
        cv2.rectangle(im, (x, y), (x+w, y+h), (0,255,0), 7)



cv2.imwrite('test/outputs/output9.jpg', im)
like image 700
Veejay Avatar asked Oct 22 '17 21:10

Veejay


People also ask

How do I save an edited image in OpenCV?

When working with OpenCV Python, images are stored in numpy ndarray. To save an image to the local file system, use cv2. imwrite() function of opencv python library.


1 Answers

You can just extract the rectangle ROI into another image object and save that object using imwrite.

roi = im[y:y+h, x:x+w]
cv2.imwrite("roi.jpg", roi)
like image 56
Lakshya Kejriwal Avatar answered Sep 20 '22 11:09

Lakshya Kejriwal