【问题标题】:Optimal way to resize an image with OpenCV Python使用 OpenCV Python 调整图像大小的最佳方法
【发布时间】:2019-11-13 10:01:30
【问题描述】:
我想根据百分比调整图像大小,并使其尽可能接近原始图像,同时尽量减少噪点和失真。调整大小可以向上或向下,因为我可以缩放到原始图像大小的 5% 或 500%(或作为示例给出的任何其他值)
这是我尝试过的,我需要对调整后的图像进行绝对最小的更改,因为我将使用它与其他图像进行比较
def resizing(main,percentage):
main = cv2.imread(main)
height = main.shape[ 0] * percentage
width = crop.shape[ 1] * percentage
dim = (width,height)
final_im = cv2.resize(main, dim, interpolation = cv2.INTER_AREA)
cv2.imwrite("C:\\Users\\me\\nature.jpg", final_im)
【问题讨论】:
标签:
python
image
opencv
python-imaging-library
image-resizing
【解决方案1】:
我认为您正在尝试调整大小并保持纵横比。这是一个根据百分比放大或缩小图像的函数
原图示例
将图像大小调整为 0.5 (50%)
将图像大小调整为 1.3 (130%)
import cv2
# Resizes a image and maintains aspect ratio
def maintain_aspect_ratio_resize(image, width=None, height=None, inter=cv2.INTER_AREA):
# Grab the image size and initialize dimensions
dim = None
(h, w) = image.shape[:2]
# Return original image if no need to resize
if width is None and height is None:
return image
# We are resizing height if width is none
if width is None:
# Calculate the ratio of the height and construct the dimensions
r = height / float(h)
dim = (int(w * r), height)
# We are resizing width if height is none
else:
# Calculate the ratio of the width and construct the dimensions
r = width / float(w)
dim = (width, int(h * r))
# Return the resized image
return cv2.resize(image, dim, interpolation=inter)
if __name__ == '__main__':
image = cv2.imread('1.png')
cv2.imshow('image', image)
resize_ratio = 1.2
resized = maintain_aspect_ratio_resize(image, width=int(image.shape[1] * resize_ratio))
cv2.imshow('resized', resized)
cv2.imwrite('resized.png', resized)
cv2.waitKey(0)
【解决方案2】:
你可以使用cv2.resize这个语法:
cv2.resize(image,None,fx=int or float,fy=int or float)
fx 取决于宽度
fy 取决于高度
你可以把第二个参数None或(0,0)
例子:
img = cv2.resize(oriimg,None,fx=0.5,fy=0.5)
注意:
0.5 表示要缩放图像的 50%