-2

I try to play a ROI of the window as shown in the picture by receiving the image with the Webcam.

- Conditions

1) The size of the main window is 400x300.

2) ROI is set to 320x240 at (30,30).

3) Put a red border on the ROI.

enter image description here

Here is how I did it:

  1. Create a mask with the same size as the frame.
  2. Make a square ROI on the mask.
  3. Use cv2.add to synthesize frame and mask, and assign it to dst.
  4. Check dst with cv2.imshow.

Here is code

import numpy as np, cv2
capture = cv2.VideoCapture(0)
if capture.isOpened() is None:
    raise Exception("Camera not connected")

capture.set(cv2.CAP_PROP_FRAME_WIDTH, 300)
capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 400)

while True:
    ret, frame = capture.read()
    
    if not ret:
        break

    mask = np.zeros(frame.shape[:2], np.uint8)

    cv2.rectangle(mask, (30, 30), (320, 240), (0, 0, 255), -1)

    dst = cv2.add(frame, frame, mask = mask)

    cv2.imshow("mask", mask)
    cv2.imshow("frame", frame)
    cv2.imshow("dst", dst)

    if cv2.waitKey(10) == 27:
        break
    

capture.release()
cv2.destroyAllWindows()

But, I don't solve it

Any other way?

Thanks for the feedback.

Joon
  • 1
  • 1

1 Answers1

0

A mask has only one channel. Change this line:

cv2.rectangle(mask, (30, 30), (320, 240), 255, -1)

Additionally you shouldn't use cv2.add() because it changes your image. Better do:

dst = cv2.bitwise_and(frame, frame, mask=mask)

And this is how you can simply crop the image, if you need to:

dst = frame[30:240, 30:320]

Regarding the setting of frame width and height please read this.

Markus
  • 5,976
  • 5
  • 6
  • 21