0

I am using this code to create a mask which split every image in half (left-right).

import cv2
import numpy as np

image = cv2.imread('box.png')

h = image.shape[0]
w = image.shape[1]

mask_l = np.zeros(image.shape[:2], dtype="uint8")

roi = cv2.rectangle(mask_l, (w//2, 0), (0, h), 255, -1)  # LEFT MASK

masked_l = cv2.bitwise_and(image, image, mask=mask_l)
cv2.imshow("Left", masked_l)
cv2.waitKey(0)


mask_r = np.zeros(image.shape[:2], dtype="uint8")

cv2.rectangle(mask_r, (w//2, 0), (w, h), 255, -1)  # RIGHT MASK

masked_r = cv2.bitwise_and(image, image, mask=mask_r)
cv2.imshow("Right", masked_r)
cv2.waitKey(0)

How can I save the visible part of the image to a ROI ? Possible, if the saved rectangle take the name as source image as part of filename. Es: input --> box.png --> output --> box1.png, box2.png

Thanks

3
  • Crop the image and use cv2.imwrite(). Also update with sample input and sample output Commented Dec 29, 2017 at 10:42
  • As input/output you can use any image you want, there is no a specific one. Commented Dec 29, 2017 at 10:43
  • @ZdaR is this, how do I crop the visible area ? Using cropped = image[w//2:0, 0:h] doesn't work... Commented Dec 29, 2017 at 10:55

1 Answer 1

1

I did it...

import cv2
import numpy as np
import os

image = cv2.imread('box.png')

path, filename = os.path.split('box.png')
filename = (filename[:-4])

root_path = 'C:\\Users\\Link\\Desktop\\'

h = image.shape[0]
w = image.shape[1]

mask_l = np.zeros(image.shape[:2], dtype="uint8")

roi = cv2.rectangle(mask_l, (w//2, 0), (0, h), 255, -1)  # LEFT MASK

masked_l = cv2.bitwise_and(image, image, mask=mask_l)

list = ['a', 'b']

for i in enumerate(masked_l):
    x, y, w, h = cv2.boundingRect(mask_l)
    roi_l = image[y:y + h, x:x + w]
    cv2.imwrite(root_path + str(filename) + '{}.png'.format(lista[0]), roi_l)

cv2.imshow("Left", roi_l)
cv2.waitKey(0)


h2 = image.shape[0]
w2 = image.shape[1]

mask_r = np.zeros(image.shape[:2], dtype="uint8")

cv2.rectangle(mask_r, (w2//2, 0), (w2, h2), 255, -1)  # RIGHT MASK

masked_r = cv2.bitwise_and(image, image, mask=mask_r)

for i_i in enumerate(masked_r):
    x2, y2, w2, h2 = cv2.boundingRect(mask_r)
    roi_r = image[y2:y2 + h2, x2:x2 + w2]

    cv2.imwrite(root_path + str(filename) + '{}.png'.format(lista[1]), roi_r)

cv2.imshow("Right", roi_r)
cv2.waitKey(0)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.