gpt4 book ai didi

python - 扩展 PIL 的 c 功能

转载 作者:太空宇宙 更新时间:2023-11-04 01:40:44 24 4
gpt4 key购买 nike

我想使用不同的混合算法创建类似于 PIL 的 Image.blend 的功能。为此,我需要:(1) 直接修改 PIL 模块并编译我自己的自定义 PIL 或 (2) 编写一个导入和扩展 PIL 的 python c 模块?

我试过没有成功:

#include "_imaging.c"

我还试图从 PIL 源中提取我需要的部分并将它们放入我自己的文件中。我得到的越多,我必须拉动的东西就越多,这似乎不是理想的解决方案。

更新:编辑以添加在 python 中实现的混合算法(这模拟了 Photoshop 中的叠加混合模式):

def overlay(upx, lpx):
return (2 * upx * lpx / 255 ) if lpx < 128 else ((255-2 * (255 - upx) * (255 - lpx) / 255))

def blend_images(upper = None, lower = None):
upixels = upper.load()
lpixels = lower.load()
width, height = upper.size
pixeldata = [0] * len(upixels[0, 0])
for x in range(width):
for y in range(height):
# the next for loop is to deal with images of any number of bands
for i in range(len(upixels[x,y])):
pixeldata[i] = overlay(upixels[x, y][i], lpixels[x, y][i])
upixels[x,y] = tuple(pixeldata)
return upper

我也没有成功地尝试使用 scipy 的 weave.inline 实现它:

def blend_images(upper=None, lower=None):
upixels = numpy.array(upper)
lpixels = numpy.array(lower)
width, height = upper.size
nbands = len(upixels[0,0])
code = """
#line 120 "laplace.py" (This is only useful for debugging)
int upx, lpx;
for (int i = 0; i < width-1; ++i) {
for (int j=0; j<height-1; ++j) {
for (int k = 0; k < nbands-1; ++k){
upx = upixels[i,j][k];
lpx = lpixels[i,j][k];
upixels[i,j][k] = ((lpx < 128) ? (2 * upx * lpx / 255):(255 - 2 * (255 - upx) * (255 - lpx) / 255));
}
}
}
return_val = upixels;
"""
# compiler keyword only needed on windows with MSVC installed
upixels = weave.inline(code,
['upixels', 'lpixels', 'width', 'height', 'nbands'],
type_converters=converters.blitz,
compiler = 'gcc')
return Image.fromarray(upixels)

我在 upixellpixel 数组上做错了,但我不确定如何修复它们。我对 upixels[i,j][k] 的类型有点困惑,不确定我可以将它分配给什么。

最佳答案

这是我在 NumPy 中的实现.我没有单元测试,所以我不知道它是否包含错误。我想如果它失败了我会收到你的消息。正在发生的事情的解释在评论中。它在 0.07 秒内处理 200x400 RGBA 图像

import Image, numpy

def blend_images(upper=None, lower=None):
# convert to arrays
upx = numpy.asarray(upper).astype('uint16')
lpx = numpy.asarray(lower).astype('uint16')
# do some error-checking
assert upper.mode==lower.mode
assert upx.shape==lpx.shape
# calculate the results of the two conditions
cond1 = 2 * upx * lpx / 255
cond2 = 255 - 2 * (255 - upx) * (255 - lpx) / 255
# make a new array that is defined by condition 2
arr = cond2
# this is a boolean array that defines where in the array lpx<128
mask = lpx<128
# populate the parts of the new arry that meet the critera for condition 1
arr[mask] = cond1[mask]
# prevent overflow (may not be necessary)
arr.clip(0, 255, arr)
# convert back to image
return Image.fromarray(arr.astype('uint8'), upper.mode)

关于python - 扩展 PIL 的 c 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5161510/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com