Skip to main content
 首页 » 编程设计

python之如何强制将我所有的值从 uint8 转换为 int 而不是 int64

2025年05月04日31lautakyan007

我有一个大小为 112 * 92 的 numpy ndarray。这基本上是使用 cv2.imread 读取的灰度图像。由于它的灰度,所以它的最大值是 255。

我正在尝试使用 phe paillier 库加密此数组:http://python-paillier.readthedocs.io/en/stable/usage.html#role-1

但是当我运行 public_key.encrypt() 命令时出现错误:

Traceback (most recent call last): 
  File "/usr/lib/python3.5/code.py", line 91, in runcode 
    exec(code, self.locals) 
  File "<input>", line 1, in <module> 
  File "<input>", line 1, in <listcomp> 
  File "/usr/local/lib/python3.5/dist-packages/phe/paillier.py", line 169, in encrypt 
    encoding = EncodedNumber.encode(self, value, precision) 
  File "/usr/local/lib/python3.5/dist-packages/phe/encoding.py", line 176, in encode 
    % type(scalar)) 
TypeError: Don't know the precision of type <class 'numpy.uint8'>. 

我尝试使用 float 和 int64 并且我不断收到相同的错误,除了最后一行中的类更改。

奇怪的是,如果我在他们的网站上运行手动输入列表的示例,它会完美运行。我的 numpy 数组和他们的示例之间我能理解的唯一区别是类型。

在检查器中检查时,它们的类型是 int 而我的是 uint8。

secret_number_list = [3.141592653, 300, -4.6e-12] 
type(secret_number_list) 
<class 'list'> 
type(secret_number_list[1]) 
<class 'int'> 

而如果我对我的阵列做同样的事情,我会得到:

type(image) 
<class 'numpy.ndarray'> 
type(image[0][0]) 
<class 'numpy.uint8'> 

我尝试使用 image.astype(int) 将其转换为 int 但我得到了一个 int64 类型,它给出了相同的错误加密。

有没有办法将所有值都转换为 int 而不是 int64?

请您参考如下方法:

据我所知(您可以在 the sources here 中看到),您应该只传递 int 或 float。因此,您需要将 ndarray 转换为包含 int 或 float 项的嵌套列表。参见 ndarray.tolist .

例如:

>>> a = np.array([[1, 2], [3, 4]]) 
>>> b = a.tolist() 
>>> type(a) 
<class 'numpy.ndarray'> 
>>> type(b) 
<class 'list'> 
>>> type(a[0][0]) 
<class 'numpy.int64'> 
>>> type(b[0][0]) 
<class 'int'>