def read_img(in_filename, grayscale=False, extra_info={}):
"""Returns the image saved at in_filename as a numpy array.
If grayscale is True, converts from 3D RGB image to 2D grayscale image.
"""
if is_pypy:
ans = Image.open(in_filename)
height = ans.height
width = ans.width
channels = len(ans.getbands())
if ans.mode == 'I':
numpy_mode = 'uint32'
maxval = 65535.0
elif ans.mode in ['L', 'RGB', 'RGBA']:
numpy_mode = 'uint8'
maxval = 255.0
else:
raise ValueError('unknown mode')
ans = numpy.fromstring(ans.tobytes(), numpy_mode).reshape((height, width, channels))
ans = ans/maxval
if grayscale and (len(ans.shape) == 3 and ans.shape[2] == 3):
ans = ans[:,:,0]*0.2125 + ans[:,:,1]*0.7154 + ans[:,:,2]*0.0721
if len(ans.shape) == 3 and ans.shape[2] == 1:
ans = ans[:,:,0]
return ans
else:
ans = skimage.io.imread(in_filename)
if ans.dtype == numpy.int32: # Work around scikit-image bug #1680
ans = numpy.asarray(ans, numpy.uint16)
ans = skimage.img_as_float(ans)
if grayscale:
ans = skimage.color.rgb2gray(ans)
# print('here', use_4channel, len(ans.shape) == 3, ans.shape[2] == 3)
if use_4channel and len(ans.shape) == 3 and ans.shape[2] == 3:
ans = numpy.dstack((ans,) + (numpy.ones((ans.shape[0], ans.shape[1], 1)),))
extra_info['originally_3channel'] = True
return ans
评论列表
文章目录