代码之家  ›  专栏  ›  技术社区  ›  StuckInPhDNoMore

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

  •  1
  • StuckInPhDNoMore  · 技术社区  · 8 年前

    我有点麻木 ndarray 大小 112 * 92 . 这基本上是一个灰度图像读取使用 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'>
    

    我试着把这个转换成 int 通过使用 image.astype(int) 但我有一个 英特64 在加密时给出相同错误的类型。

    有没有一种方法可以将所有值转换为 int 而不是 英特64 ?

    2 回复  |  直到 8 年前
        1
  •  2
  •   Colin Dickie    8 年前

    尝试列表理解以生成一个嵌套的python列表 int 然后转换回一个numpy数组:

    import numpy
    import cv2
    from phe import paillier
    
    
    openfilename = "/path/to/image.jpg"
    img = cv2.imread(openfilename,0)
    
    public_key, private_key = paillier.generate_paillier_keypair()
    
    encrypted_number_list = [[public_key.encrypt(int(x)) for x in row] for row in img]
    encrypted_number_array = numpy.array(encrypted_number_list)
    print(encrypted_number_array)
    

    对于大图像来说这会非常慢

        2
  •  3
  •   Oleh Rybalchenko    8 年前

    据我所知 the sources here )您只能通过 int float . 所以你需要转换 ndarray 到嵌套列表 int 浮动 项目。见 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'>