【发布时间】:2021-08-18 02:50:45
【问题描述】:
我尝试手动调整图像的对比度。第二个代码对我来说很好,但它使用循环->它很慢,所以我更改为第一个代码但得到不同的输出。
我不知道出了什么问题,因为我认为这两个是相似的。有人能告诉我我错过了什么吗?非常感谢。
无循环代码
from PIL import Image
# level should be in range of -255 to +255 to decrease or increase contrast
def change_contrast(img, level):
def truncate(v):
v[v<0] = 0
v[v>255] = 255
return v
img_c = np.reshape(img,(1,img.shape[0] *img.shape[1],3))[0].copy()
factor = (259 * (level+255)) / (255 * (259-level))
img_c = factor * (img_c-128) + 128
img_c = truncate(img_c)
return np.reshape(img_c,(img.shape[0] ,img.shape[1],3)).astype(np.uint8)
带循环的代码
from PIL import Image
# level should be in range of -255 to +255 to decrease or increase contrast
def change_contrast(img, level):
def truncate(v):
v[v<0] = 0
v[v>255] = 255
return v
img_c = np.reshape(img,(1,img.shape[0] *img.shape[1],3))[0].copy()
factor = (259 * (level+255)) / (255 * (259-level))
for x in range(img_c.shape[0]):
color = img_c[x]
new_color = truncate(np.asarray([int(factor * (c-128) + 128) for c in color]))
img_c[x]= new_color
return np.reshape(img_c,(img.shape[0] ,img.shape[1],3))
测试代码
a = PIL.Image.open('Test.jpg')
b = np.asarray(a)
Image.fromarray(change_contrast(b , 128))
结果:
非循环:
循环:
解决方案:我的原始数组有 uint8 类型,它不会让你有负数(例如:img_c - 128)。更改为 int 应该会有所帮助!
必须更仔细地检查类型。
【问题讨论】:
-
我会继续投票,因为你已经按照说明如何提出正确的问题了。用户名签出。继续努力。
标签: python numpy image-processing python-imaging-library