# Create a ZOOM-PAN effect using OpenCV and Python. Am image is read and the # effect can be created either about the centre of the image or about any # specified point. This code is equivalent to FFmpeg commands for zoom-in and # zoom-out effect described below. This effect is also called Ken Burns effect. #Start with original dimension and zoom-in 0.0015 every iteration #ffmpeg -loop 1 -i image.png -vf "zoompan=z='min(zoom+0.0015,1.5)':d=125" -c:v libx264 -t 5 -s "800x450" -y zoomedIn.mp4 #Start zoomed in at 1.5 and zoom out 0.0015 every iteration #ffmpeg -loop 1 -i image.png -vf "zoompan= z='if(lte(zoom,1.0),1.5, max(1.001, zoom-0.0015))':d=125" -c:v libx264 -t 5 -s "800x450" -y zoomedout.mp4 import cv2 imgName = 'image.png' vidName = "zoomedIn.mp4" nfs = 20 #Number of Frames per Second, video duration = nframe/nfs nframe = 100 #Total number of frames in the output vidoe max_zoom = 2.0 #Maximum Zoom level (should be > 1.0) max_rot = 30 #Maximum rotation in degrees, set '0' for no rotation #Define the function for zooming effect def zoomPan(img, zoom=1, angle=0, coord=None): cy, cx = [i/2 for i in img.shape[:-1]] if coord is None else coord[::-1] rot = cv2.getRotationMatrix2D((cx, cy), angle, zoom) res = cv2.warpAffine(img, rot, img.shape[1::-1], flags=cv2.INTER_LINEAR) return res img = cv2.imread(imgName) w = img.shape[1] h = img.shape[0] codec = cv2.VideoWriter_fourcc(*'mp4v') #other formats can be DIVX or DIVD video = cv2.VideoWriter(vidName, codec, nfs, (w, h)) #Make the loop for Zooming-in i = 1 while i < nframe: zLvl = 1.0 + i / (1/(max_zoom-1)) / nframe angle = i * max_rot / nframe zoomedImg = zoomPan(img, zLvl, angle, coord=None) video.write(zoomedImg) i = i + 1 #Make the loop for Zooming-out to starting position i = nframe while i > 0: zLvl = 1.0 + i / (1/(max_zoom-1)) / nframe angle = i * max_rot / nframe zoomedImg = zoomPan(img, zLvl, angle, coord=None) video.write(zoomedImg) i = i - 1 video.release()