Reputation: 35
I’m trying to use opencv to take a photo on a 1080p camera, however, only want the photo to be 224x224 pixels. How can I use opencv to do this.
I currently have the following code:
Import cv2
Cap = cv2.VideoCam(0)
Cap.set(3, 224)
Cap.set(4, 224)
Ret, frame = cap.read()
However when I look at the shape of frame, it is not (224, 224, 3). Could someone please help me figure out how to make it output the dimensions of pixels I want
Upvotes: 2
Views: 1449
Reputation: 207405
When you say you want a 224x224 image, it depends what you mean. If we start with this image which is 1920x1080, you might want:
So, assume in the following that you have read your frame from the camera into a variable called im
using something like:
...
...
ret, im = cap.read()
If you want (A), use:
# If you want the top-left corner
good = im[:224, :224]
If you want (B), use:
# If you want the centre
x = h//2 - 112
y = w//2 - 112
good = im[x:x+224, y:y+224]
If you want (C), use:
# If you want the largest square, scaled down to 224x224
y = (w-h)//2
good = im[:, y:y+h]
good = cv2.resize(good,(224,224))
If you want (D), use:
# If you want the entire frame distorted to fit 224x224
good = cv2.resize(im,(224,224))
Keywords: Image processing, video, 1920x1080, 1080p, crop, distort, largest square, central portion. top-left, Python, OpenCV, frame, extract.
Upvotes: 5
Reputation: 736
import cv2
video_capture = cv2.VideoCapture(0)
while video_capture.isOpened():
video_capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 224)
video_capture.set(cv2.CAP_PROP_FRAME_WIDTH, 224)
frame = video_capture.read()[1]
cv2.imshow('frame', frame)
if cv2.waitKey(1) == ord("q"):
break
to get the current size use :
cap.get(cv2.CAP_PROP_FRAME_WIDTH)
cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
if that didn't work then Opencv doesn't have access to the (width, height )features of the camera you are using.
Upvotes: 1
Reputation: 231
This is quite simple, just use the cv2.resize(frame, size)
function. Example:
import cv2
cam = cv2.VideoCapture(0) # My camera is 640x480
size = (200,200) # The "size" parameter must be a tuple.
while True:
frame = cam.read()[1]
new_frame = cv2.resize(frame,size) # Resizing the frame ...
cv2.imshow('sla',new_frame)
if cv2.waitKey(1) == ord("q"):
break
cv2.destroyAllWindows()
Upvotes: 0