【问题标题】:Numpy: How to prevent circular looping to highest value when subtracting from the least valueNumpy:从最小值减去时如何防止循环循环到最大值
【发布时间】:2018-06-06 14:41:56
【问题描述】:
image = cv2.imread('black.jpg')[:,:,0] # let's just take the red channel alone for brevity
print(image[75:85,155:165]) # print middle 10x10
# output: [[0,0,0,....],...]

我想从所有像素强度中减去 1。是的,我绝对不希望 0 变成 255。我只是希望他们保持为 0。

print(image[75:85,155:165]-1)
# output: [[255,255,255,....],...]

print(np.array(image[75:85,155:165])-1)
# output: [[255,255,255,....],...]

print(np.array(image[75:85,155:165], dtype='float32')-1)
# output: [[-1.,-1.,-1.,....],...]

我可以在.clip(0,255) 之后将最后一个转换回uint8,但这感觉不是正确的做法。有没有办法直接做到这一点(没有强制转换和可能对并行处理无效的条件)?

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    最好的方法是 np.where 带面具:

    grey_new = np.where(image == 0, 0, image - 1)
    

    您可以在 this answernumpy.where 文档中找到更多信息。

    【讨论】:

    • 这应该比减去然后选择等于 255 的东西并将它们设为 0 更快,不是吗?
    【解决方案2】:

    一个简单的选择是:

    image[75:85,155:165] - 1 * (image[75:85,155:165] > 0)
    

    【讨论】:

      【解决方案3】:

      由于您将所有值都删除了 1,因此只有 0 值将变为 255。那么,您可以做的就是将它们恢复为 0:

      a = np.array(image[75:85,155:165])-1
      a[a==255] = 0
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-27
        • 2019-03-12
        • 2016-06-07
        • 1970-01-01
        • 2022-09-29
        • 2017-09-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多