【问题标题】:Inverting numpy array image which might be uint8, uint16,反转可能是 uint8、uint16 的 numpy 数组图像,
【发布时间】:2013-06-27 05:39:06
【问题描述】:

有没有更漂亮的方法来做到这一点?具体来说,这些最大值是否可以通过 numpy API 获得?我无法在 API 中找到它们,尽管很容易找到它们 here in the docs

MAX_VALUES = {np.uint8: 255, np.uint16: 65535, np.uint32: 4294967295, \
              np.uint64: 18446744073709551615}

try:
    image = MAX_VALUES[image.dtype] - image
except KeyError:
    raise ValueError, "Image must be array of unsigned integers."

像 PIL 和 cv2 这样的包提供了方便的工具来反转图像,但是在代码中的这一点上,我有一个 numpy 数组——接下来是更复杂的分析——我想坚持使用 numpy。

【问题讨论】:

    标签: python image-processing numpy


    【解决方案1】:

    试试看

    image ^= MAX_VALUES[image.dtype]
    

    【讨论】:

    • ^= 对我来说是新的,对谷歌来说很难。运营商叫什么?
    • 我相信是xor 运算符。
    【解决方案2】:

    顺便说一句,您不需要自己定义MAX_VALUES。 NumPyhas them built-in:

    import numpy as np
    h, w = 100, 100
    image = np.arange(h*w).reshape((h,w)).astype(np.uint8)
    max_val = np.iinfo(image.dtype).max
    print(max_val)
    # 255
    image ^= max_val
    
    print(image)
    # [[255 254 253 ..., 158 157 156]
    #  [155 154 153 ...,  58  57  56]
    #  [ 55  54  53 ..., 214 213 212]
    #  ..., 
    #  [ 27  26  25 ..., 186 185 184]
    #  [183 182 181 ...,  86  85  84]
    #  [ 83  82  81 ..., 242 241 240]]
    

    【讨论】:

    • 啊,iinfo 是我要找的。谢谢。
    猜你喜欢
    • 2022-07-21
    • 2021-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-12
    • 2016-06-19
    • 1970-01-01
    • 2013-02-10
    相关资源
    最近更新 更多