我有 3 个 400x600 的数组,它们代表我想要制作的图像的 3 种颜色。
我在这里找到了一个潜在的方法:http://docs.scipy.org/doc/scipy-0.13.0/reference/generated/scipy.misc.imsave.html 但他们希望我将浮点数转换为uint8。现在,如果我通过"image.dtype = np.uint8"更改dtype,则以某种方式将尺寸更改为400x600x24(而当我不更改类型时,它是400x600x3)
如何更改此设置?(其他方法也欢迎)
image.dtype = np.uint8
只是强行将字节从 float64
转换为 uint8
。由于每个float64
占用 8 个字节,而每个uint8
只有 1 个字节,因此您获得的值是其 8 倍。
若要转换值,而不是重新解释字节,您需要 astype
方法:
image = image.astype(np.uint8)
但是,出于两个原因,这可能不是很有用。首先,最大的一点,您的浮点值可能都在 0.0-1.0 范围内。其次,astype
修剪,而不是四舍五入。因此,转换为整数只会使它们几乎全部为 0,其余为 1,而不是平滑地从 0-255 范围。
所以,你可能想要的是这样的:
image = (image * 255).round().astype(np.uint8)
谢谢你@abarnert!这就是我搜索从 sklearn.datasets.fetch_olivetti_faces() 等数据集加载图像的内容,该数据集具有 float32
dtype
,值范围从 0-1 与 OpenCV 一起使用,OpenCV 使用dtype
uint8
和值范围从 0-255。
import numpy as np
import cv2 as cv
from sklearn import datasets
data = datasets.fetch_olivetti_faces()
image = data.images[15]
image
array([[0.6694215 , 0.6818182 , 0.7066116 , ..., 0.5082645 , 0.55785125, 0.58677685], [0.677686 , 0.70247936, 0.71487606, ..., 0.5289256 , 0.5495868 , 0.58264464], [0.6983471 , 0.7107438 , 0.70247936, ..., 0.5495868 , 0.55785125, 0.5785124 ], ..., [0.59917355, 0.59917355, 0.54545456, ..., 0.10743801, 0.11157025, 0.10330579], [0.59090906, 0.6198347 , 0.5785124 , ..., 0.11157025, 0.10743801, 0.10743801], [0.5661157 , 0.6280992 , 0.59917355, ..., 0.11157025, 0.11157025, 0.10743801]], dtype=float32)
img = (image * 255).round().astype(np.uint8)
img
array([[171, 174, 180, ..., 130, 142, 150], [173, 179, 182, ..., 135, 140, 149], [178, 181, 179, ..., 140, 142, 148], ..., [153, 153, 139, ..., 27, 28, 26], [151, 158, 148, ..., 28, 27, 27], [144, 160, 153, ..., 28, 28, 27]], dtype=uint8)
该img
现在已准备好在简历库中进一步处理。