gpt4 book ai didi

python - 使用 Numpy 更有效地变换色调

转载 作者:行者123 更新时间:2023-12-04 10:07:08 24 4
gpt4 key购买 nike

我正在制作一个在线图像编辑器,我正在实现一个色相/周六/明度编辑器。这是我使用给定值更改图像的功能。

def make_edit(pixels, hue, sat, lum):
shape = pixels.shape
new = np.empty(shape)
print(time.time())
for row_count, row in enumerate(pixels):
for pixel_count, p in enumerate(row):
new_hue = p[0] + hue
if new_hue < 0:
new_hue += 255
elif new_hue > 255:
new_hue -= 255

new_sat = p[1] + sat
if new_sat < 0:
new_sat += 255
elif new_sat > 255:
new_sat -= 255

new_lum = p[2] + lum
if new_lum < 0:
new_lum = 0
elif new_lum > 255:
new_lum = 255

new[row_count, pixel_count] = np.array([new_hue, new_sat, new_lum])
print(time.time())
return new

该函数采用形状为(高度、宽度、3)的 numpy 数组。我逐个像素地做,然后将色调、饱和度和亮度值添加到每个像素。然而,它需要 13 秒(在 (648, 1152, 3) 形状的阵列上),显然太长了。是否有一个 numpy 函数可以用我给它的数量来抵消所有值。
附言该功能还不起作用,hue 似乎可以,但是 sat 和 lum 没有提供正确的图像。

最佳答案

由于您还没有让 sat 和 lum 正常工作,因此可能需要根据您的最终代码的样子进行调整,但它确实与您当前过程的结果相匹配,并且速度快了几个数量级:

def getPic():   
return np.random.randint(0, 255, 648*1152*3).reshape(648, 1152, 3)

def make_edit(pixels, hue, sat, lum):
shape = pixels.shape
new = np.empty(shape)
#print(time.time())
for row_count, row in enumerate(pixels):
for pixel_count, p in enumerate(row):
new_hue = p[0] + hue
if new_hue < 0:
new_hue += 255
elif new_hue > 255:
new_hue -= 255

new_sat = p[1] + sat
if new_sat < 0:
new_sat += 255
elif new_sat > 255:
new_sat -= 255

new_lum = p[2] + lum
if new_lum < 0:
new_lum = 0
elif new_lum > 255:
new_lum = 255

new[row_count, pixel_count] = np.array([new_hue, new_sat, new_lum])
#print(time.time())
return new


def new_make_edit(pixels, hue, sat, lum):
new = np.empty_like(pixels)
new[:,:,0] = pixels[:,:,0] + hue
new[:,:,0][new[:,:,0]<0] += 255
new[:,:,0][new[:,:,0]>255] -= 255

new[:,:,1] = pixels[:,:,1] + sat
new[:,:,1][new[:,:,1]<0] += 255
new[:,:,1][new[:,:,1]>255] -= 255

new[:,:,2] = pixels[:,:,2] + lum
new[:,:,2][new[:,:,2]<0] = 0
new[:,:,2][new[:,:,2]>255] = 255
return new

def tEd():
pic = getPic()
old = make_edit(pic, 10, -25, 211)
new = new_make_edit(pic, 10, -25, 211)
return old, new

def timeOld():
pic = getPic()
old = make_edit(pic, 10, -25, 211)
return old

def timeNew():
pic = getPic()
new = new_make_edit(pic, 10, -25, 211)
return new

在同一图像上执行 old 和 new 并验证输出匹配:
>>> o,n=tEd()
>>> np.all(o==n)
True

性能对比:
>>> timeit.timeit(timeNew, number=10)
0.5608299169980455
>>> timeit.timeit(timeOld, number=10)
58.86368254100671

关于python - 使用 Numpy 更有效地变换色调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61528719/

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