我正在建立一个Python的图片库,并希望能够快速生成高分辨率图像的缩略图。
为各种图像源生成高质量缩略图的最快方法是什么?
我应该使用像imagemagick这样的外部库吗,或者有没有一种有效的内部方法来做到这一点?
调整大小的图像的尺寸将为(最大尺寸):
120x120
720x720
1600x1600
质量是一个问题,因为我想保留尽可能多的原始颜色,并尽量减少压缩伪影。
谢谢。
发布于 2011-12-26 06:35:57
你想要PIL它很容易做到这一点
from PIL import Image
sizes = [(120,120), (720,720), (1600,1600)]
files = ['a.jpg','b.jpg','c.jpg']
for image in files:
for size in sizes:
im = Image.open(image)
im.thumbnail(size)
im.save("thumbnail_%s_%s" % (image, "_".join(size)))
如果你非常需要速度。然后线程它,多处理它或获得另一种语言。
发布于 2013-11-02 01:03:43
这个问题来得有点晚(只有一年!),但我将利用@JakobBowyer的答案中的"multiprocess it“部分。
这是embarrassingly parallel问题的一个很好的例子,因为主要代码不会改变自身外部的任何状态。它只是读取一个输入,执行其计算并保存结果。
多亏了multiprocessing.Pool
提供的映射函数,Python实际上在解决这类问题上做得很好。
from PIL import Image
from multiprocessing import Pool
def thumbnail(image_details):
size, filename = image_details
try:
im = Image.open(filename)
im.thumbnail(size)
im.save("thumbnail_%s" % filename)
return 'OK'
except Exception as e:
return e
sizes = [(120,120), (720,720), (1600,1600)]
files = ['a.jpg','b.jpg','c.jpg']
pool = Pool(number_of_cores_to_use)
results = pool.map(thumbnail, zip(sizes, files))
代码的核心与@JakobBowyer完全相同,但我们将其封装在一个函数中,通过多处理map函数将其分散到多个核心中,而不是在单个线程中循环运行它。
发布于 2014-11-23 05:01:07
另一种选择是使用OpenCV的python bindings。这可能比PIL或Imagemagick更快。
import cv2
sizes = [(120, 120), (720, 720), (1600, 1600)]
image = cv2.imread("input.jpg")
for size in sizes:
resized_image = cv2.resize(image, size)
cv2.imwrite("thumbnail_%d.jpg" % size[0], resized_image)
这里有一个更完整的here演练。
如果您想并行运行它,请在Py3上使用concurrent.futures
或在Py2.7上使用futures
包:
import concurrent.futures
import cv2
def resize(input_filename, size):
image = cv2.imread(input_filename)
resized_image = cv2.resize(image, size)
cv2.imwrite("thumbnail_%s%d.jpg" % (input_filename.split('.')[0], size[0]), resized_image)
executor = concurrent.futures.ThreadPoolExecutor(max_workers=3)
sizes = [(120, 120), (720, 720), (1600, 1600)]
for size in sizes:
executor.submit(resize, "input.jpg", size)
https://stackoverflow.com/questions/8631076
复制相似问题