Home > Net >  how do I (filter and) save many ROIs taken from a larger picture individually to picture files?
how do I (filter and) save many ROIs taken from a larger picture individually to picture files?

Time:11-08

I followed this discussion: How extract pictures from an big image in python

import cv2

image = cv2.imread('/home/joy/桌面/test_11_4/original.png', cv2.IMREAD_UNCHANGED)

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
gradient = cv2.morphologyEx(gray, cv2.MORPH_GRADIENT, kernel)

contours = cv2.findContours(gradient, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[1]

for cnt in contours:
    (x,y,w,h) = cv2.boundingRect(cnt)
    aaa = cv2.rectangle(image, (x,y), (x w,y h), (0,0,255))

cv2.imwrite("/home/joy/桌面/test_11_4/output.png", aaa)

I did frame them up, then how to save each one/qr code

CodePudding user response:

I did frame them up, then how to save each one/qr code

If you want to save the contents of each rectangle, there are two steps.

Within your for loop, the first step to make a copy of the image and crop it to the size of the rectangle.

Now that you have that image extracted, the next step is to save it. You'll want to use a different filename for each one.

for cnt in contours:
    (x,y,w,h) = cv2.boundingRect(cnt)
    crop_img = image[y:y h, x:x w]
    cv2.imwrite(f"/home/joy/桌面/test_11_4/output_{x}_{y}.png", crop_img)

In this example, I'm using the X and Y coordinates of the rectangle to pick the filename.

  • Related