Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python numpy uint8像素包装解决方案_Python_Numpy - Fatal编程技术网

Python numpy uint8像素包装解决方案

Python numpy uint8像素包装解决方案,python,numpy,Python,Numpy,对于图像处理类,我在单色图像上做点运算。像素为uint8[0255] numpy uint8将包裹。例如,235+30=9。我需要像素饱和(max=255)或截断(min=0)而不是换行 我的解决方案使用int32像素进行点运算,然后转换为uint8以保存图像 这是最好的方式吗?还是有更快的办法 #!/usr/bin/python import sys import numpy as np import Image def to_uint8( data ) : # maximum p

对于图像处理类,我在单色图像上做点运算。像素为uint8[0255]

numpy uint8将包裹。例如,235+30=9。我需要像素饱和(max=255)或截断(min=0)而不是换行

我的解决方案使用int32像素进行点运算,然后转换为uint8以保存图像

这是最好的方式吗?还是有更快的办法

#!/usr/bin/python

import sys
import numpy as np
import Image

def to_uint8( data ) :
    # maximum pixel
    latch = np.zeros_like( data )
    latch[:] = 255
    # minimum pixel
    zeros = np.zeros_like( data )

    # unrolled to illustrate steps
    d = np.maximum( zeros, data )
    d = np.minimum( latch, d )

    # cast to uint8
    return np.asarray( d, dtype="uint8" )

infilename=sys.argv[1]
img = Image.open(infilename)
data32 = np.asarray( img, dtype="int32")
data32 += 30
data_u8 = to_uint8( data32 )
outimg = Image.fromarray( data_u8, "L" )
outimg.save( "out.png" )
输入图像:

输出图像:
使用:


请注意,您也可以通过以下方式在不使用numpy的情况下使图像变亮:

import ImageEnhance
enhancer = ImageEnhance.Brightness(img)
outimg = enhancer.enhance(1.2)
outimg.save('out.png')

基本上,它归结为在添加之前进行检查。例如,您可以定义如下函数:

def clip_add(arr, amt):
    if amt > 0:
        cutoff = 255 - amt
        arr[arr > cutoff] = 255
        arr[arr <= cutoff] += amt
    else:
        cutoff = -amt
        arr[arr < cutoff] = 0
        arr[arr >= cutoff] += amt
def剪辑添加(arr,amt):
如果金额>0:
截止值=255-金额
arr[arr>截止]=255
arr[arr=截止值]+=金额
您可以使用OpenCV或函数(附加说明)

不幸的是,不可能为输出阵列使用索引,因此每个图像通道的就地计算可能以这种效率较低的方式执行:

arr[..., channel] = cv2.add(arr[..., channel], 40)

clip()正是我一直需要的。谢谢我还将阅读ImageEnhance。作业是关于我们自己做点运算,但是学习其他方法会很好。在使用MNIST数据集时,我得到的
.png
图像显示了奇怪的方形伪影,而不是实际的手写数字。问题还在于数据类型
int32
。将接受的答案与
numpy.clip
astype()
转换一起使用后,一切都正常了。
>>> import numpy as np
>>> import cv2
>>> arr = np.array([100, 250, 255], dtype=np.uint8)
>>> arr
Out[1]: array([100, 250, 255], dtype=uint8)
>>> cv2.add(arr, 10, arr)  # Inplace
Out[2]: array([110, 255, 255], dtype=uint8)  # Saturated!
>>> cv2.subtract(arr, 150, arr)
Out[3]: array([  0, 105, 105], dtype=uint8)  # Truncated!
arr[..., channel] = cv2.add(arr[..., channel], 40)