![]() ![]() Return cv2.resize(image, dim, interpolation=inter)Ĭv2.imshow('width_100', maintain_aspect_ratio_resize(image, width=100))Ĭv2. # Calculate the ratio of the width and construct the dimensions # We are resizing width if height is none # Calculate the ratio of the height and construct the dimensions # We are resizing height if width is none # Return original image if no need to resize # Grab the image size and initialize dimensions Here's a function to upscale or downscale an image by desired width or height while maintaining aspect ratio # Resizes a image and maintains aspect ratioĭef maintain_aspect_ratio_resize(image, width=None, height=None, inter=cv2.INTER_AREA): Thumbnail = cv.resize(im, (round(width / 10), round(height / 10)), interpolation=cv.INTER_AREA) Using your code with cv2 import cv2 as cv Img = cv2.resize(img, None, fx=scaling_factor, fy=scaling_factor, interpolation=cv2.INTER_AREA) Scaling_factor = max_width / float(width) If max_width/float(width) < scaling_factor: Scaling_factor = max_height / float(height) If max_height < height or max_width < width: # only shrink if img is bigger than required Example shrink image to fit a max height/width (keeping aspect ratio) import cv2 To shrink an image, it will generally look best with INTER_AREA interpolation, whereas to enlarge an image, it will generally look best with INTER_CUBIC (slow) or INTER_LINEAR (faster but still looks OK). Where fx is the scaling factor along the horizontal axis and fy along the vertical axis. The new size can be specified:ĭst = cv2.resize(src, (2*width, 2*height), interpolation = cv2.INTER_CUBIC)ĭst = cv2.resize(src, None, fx = 2, fy = 2, interpolation = cv2.INTER_CUBIC), Here the input image is supposed to be scaled down which is illustrated with help of an example.There are two ways to resize an image. Implementation: Considering the below image as an input image that is supposed to be scaled producing a new output image. Suppose the user wants to reduce the image by a factor of 2 in each direction, then the syntax for calling the function is as follows resize(src, dst, Size(), 0.5, 0.5, interpolation) Suppose the user wants to resize src so that it fits the pre-created destination file, then the syntax for calling the function is as follows resize(src, dst, dst.size(), 0, 0, interpolation) Scale and write using the above object created.Create an image/2D matrix using the object.Read the image(2D matrix) from the directory.resize(src, dsize, dst, fx, fy, interpolation) Parameters src: It is the source image. Based on the requirement, the aspect ratio of an image can be preserved. Resizing, by default, only changes the width and the height of the image. INTER_LINEAR Interpolation is best for enlarging the image To resize an image in Python, resize() function of the OpenCV library is used. ![]()
0 Comments
Leave a Reply. |