numpy uint8像素包装解决方案 [英] numpy uint8 pixel wrapping solution
本文介绍了numpy uint8像素包装解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于图像处理课程,我正在对单色图像进行点运算.像素为uint8 [0,255].
For an image processing class, I am doing point operations on monochrome images. Pixels are uint8 [0,255].
numpy uint8将自动换行.例如235 + 30 =9.我需要使像素饱和(max = 255)或截断(min = 0)而不是包装.
numpy uint8 will wrap. For example, 235+30 = 9. I need the pixels to saturate (max=255) or truncate (min=0) instead of wrapping.
我的解决方案将int32像素用于点数学运算,然后转换为uint8以保存图像.
My solution uses int32 pixels for the point math then converts to uint8 to save the image.
这是最好的方法吗?还是有更快的方法?
Is this the best way? Or is there a faster way?
#!/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" )
输入图片:
Input image:
输出图像:
Output image:
推荐答案
查看全文