简体   繁体   English

将图像的分辨率降低到 Python 中的特定像素数

[英]Lower the resolution of an image to a specific number of pixels in Python

I'm trying to lower the resolution of images to 250.000 pixels using Python but I don't want them to have a specific height or width so that it depends on the image in question.我正在尝试使用 Python 将图像的分辨率降低到 250.000 像素,但我不希望它们具有特定的高度或宽度,因此它取决于相关图像。 I've been looking at options like resize_thumbnail or use Pillow but in both I have to set the maximum width or height.我一直在寻找resize_thumbnail或使用 Pillow 之类的选项,但在两者中我都必须设置最大宽度或高度。

You must know the resolution of the image you begin with, therefore scaling it to 250k pixels is just a matter of proportions.您必须知道您开始使用的图像的分辨率,因此将其缩放到 250k 像素只是一个比例问题。

# With Pillow you can read the size property of the image
width, height = image.size
res_0 = width * height
res_1 = 250000

# You need a scale factor to resize the image to res_1
scale_factor = (res_1/res_0)**0.5
resized = image.resize(width * scale_factor, height * scale_factor)

Out of curiosity I digged a little deeper to resize to the highest resolution that keeps the aspect ratio of the original image, if it exists.出于好奇,我深入挖掘以调整为保持原始图像纵横比(如果存在)的最高分辨率。
An image with an aspect ratio of W:H can be divided in W×H squares whose side is the GCD of the width and height of the resolution.宽高比为 W:H 的图像可以划分为 W×H 的正方形,其边是分辨率的宽度和高度的 GCD。
After finding W and H, what's left to do is to calculate the highest multiples of W and H that fit the given resolution, in our case 250k pixels.在找到 W 和 H 之后,剩下要做的是计算适合给定分辨率的 W 和 H 的最高倍数,在我们的例子中是 250k 像素。

import math

# With Pillow you can read the size property of the image  
width, height = 2538, 1080
res_0 = width * height
res_1 = 1920*1080 # 518400

# You need a scale factor to resize the image to Res1
scale_factor = (res_1/res_0)**0.5
ratio = width/height

# The 
max_width = width * scale_factor
max_height = height * scale_factor

# Greates Common Divider and W:H
GCD = math.gcd(width, height)
W = width / GCD
H = height / GCD

ratio_width = math.floor(max_resized[0] / W) * W
ratio_height = math.floor(max_resized[1] / H) * H

scaled_size = (max_width, max_height)
# If GCD > 1 the image can be scaled keeping the original aspect ratio
# otherwise it'll approximated
if (GCD > 1):
    scaled_size = (ratio_width, ratio_height)
    
resized = image.resize(scaled_size)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM