S Andrew
S Andrew

Reputation: 7198

How to set frame height and width in OpenCV Python

I am working on opencv python project on raspberry pi 4(pi). Pi is connected to a screen of having resolution 800x480. Picamera is also connected to pi to get live video feed. I need to show the video feed on right side of the frame and some information on left side of the frame. For this I have below code:

frame = cap.read()

frame = imutils.resize(frame, width=400, height=480)
frame2 = np.zeros((frame.shape[0], 400, frame.shape[2]), dtype=frame.dtype)

(H, W) = frame.shape[:2]
(H1, W1) = frame2.shape[:2]
print("Frame {}, {}".format(H, W))
print("Frame2 {}, {}".format(H1, W1))


cv2.putText(frame2, "Some Information", (5, 30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 1)
cv2.putText(frame2, "More Information", (5, 60), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 1)
cv2.putText(frame2, "Some More Information", (5, 90), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 1)

image = np.hstack((frame2, frame))

cv2.namedWindow(win_name, cv2.WINDOW_NORMAL)
cv2.setWindowProperty(win_name, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
cv2.imshow(win_name, image)

key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
    break

Code Explaination:

I have resized frame to 400x480 because total width we have is 800 so I will divide it into two equal parts, keeping height as same 480. This frame will show video feed on right side. I have also created frame2 which will show the information on the left. I have also kept its width as 400, not sure how to set height in this. Running this code I am getting below output:

enter image description here

As you can see output frame is divided equally into two parts having width 400 but height has been reduced to 300, as the print output says

Frame 300, 400
Frame2 300, 400

Can anyone please explain why height is reduced to 300 instead of 480. Is there any way I can keep the height to 480. Please help. Thanks

Upvotes: 1

Views: 5419

Answers (1)

rayryeng
rayryeng

Reputation: 104474

imutils.resize does not actually resize the image by using the desired width and height. It uses one or the other to scale the image. Because of the logic in the function, it has preference over the width than the height so the desired image gets resized to a width of 400, but the height is resized to 300 to keep the aspect ratio of the original frame intact. In other words, it resizes the image in a way that preserves the aspect ratio. I found the source for imutils.resize from OpenCV forums here: https://answers.opencv.org/question/208857/what-is-the-difference-between-cv2resize-and-imutilsresize/

If it is your desire to resize the images to 480 x 400, use cv2.resize instead:

frame = cv2.resize(frame, (400, 480))

Upvotes: 1

Related Questions