How to resize frame's from video with aspect ratio
Instead of using hard-coded values 640 and 480, you can divide the original frame height and width by a value and supply that as an argument, like so:
import cv2
vidcap = cv2.VideoCapture("/path/to/video")
success, image = vidcap.read()
count = 0
while success:
height, width, layers = image.shape
new_h = height / 2
new_w = width / 2
resize = cv2.resize(image, (new_w, new_h))
cv2.imwrite("%03d.jpg" % count, resize)
success, image = vidcap.read()
count += 1
Please try this.. It should give you the expected output.
def resize_image(image, width, height,COLOUR=[0,0,0]):
h, w, layers = image.shape
if h > height:
ratio = height/h
image = cv2.resize(image,(int(image.shape[1]*ratio),int(image.shape[0]*ratio)))
h, w, layers = image.shape
if w > width:
ratio = width/w
image = cv2.resize(image,(int(image.shape[1]*ratio),int(image.shape[0]*ratio)))
h, w, layers = image.shape
if h < height and w < width:
hless = height/h
wless = width/w
if(hless < wless):
image = cv2.resize(image, (int(image.shape[1] * hless), int(image.shape[0] * hless)))
else:
image = cv2.resize(image, (int(image.shape[1] * wless), int(image.shape[0] * wless)))
h, w, layers = image.shape
if h < height:
df = height - h
df /= 2
image = cv2.copyMakeBorder(image, int(df), int(df), 0, 0, cv2.BORDER_CONSTANT, value=COLOUR)
if w < width:
df = width - w
df /= 2
image = cv2.copyMakeBorder(image, 0, 0, int(df), int(df), cv2.BORDER_CONSTANT, value=COLOUR)
image = cv2.resize(image,(1280,720),interpolation=cv2.INTER_AREA)
return image