700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > python opencv压缩图片大小_使用OpenCV Python调整图像大小的最佳方法

python opencv压缩图片大小_使用OpenCV Python调整图像大小的最佳方法

时间:2023-11-01 11:34:07

相关推荐

python opencv压缩图片大小_使用OpenCV Python调整图像大小的最佳方法

我想你是想调整和保持纵横比。这里有一个函数可以根据百分比来放大或缩小图像

原始图像示例

将图像大小调整为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)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。