Python 通过逻辑索引进行 OpenCV 阈值化

Python OpenCV thresholding by logical indexing

我正在尝试对灰度图像中的某些值设置阈值。到目前为止,我已经成功输入了一定范围的数字,但我想取 50 到 150 之间的值并将它们乘以 1.2。我不确定如何访问向量中的数字,然后将其乘以 1.2。

myimg[myimg <= 50] = 0
myimg[myimg > 150 ] = 255
myimg[50<myimg<=150] = myimg * 1.2 #this line produces this error: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 

这里有三种可能的方法。

第一个简单地将图像乘以系数 1.2,将阈值乘以系数 1.2,然后使用新的阈值。

第二个将图像乘以系数 1.2,根据阈值创建一个蒙版。使用蒙版使图像在所需区域变成黑色和白色。

第三种方法更像你想要的,而不必处理整个图像。

输入(线性渐变图像):

import cv2
import numpy as np

# read image as grayscale
img = cv2.imread('grad.png', cv2.COLOR_BGR2GRAY)

# Method 1

# set threshold values
tlow = 50
thigh = 150

# multiply image by 1.2
result1 = img.copy()
result1 = (1.2 * result1).clip(0,255).astype(np.uint8)

# compute modified threshold values
tlow = int(1.2 * tlow)
thigh = int(1.2 * thigh)
result1[result1 <= tlow] = 0
result1[result1 > thigh ] = 255
print(tlow, thigh)


# Method 2

# set threshold values
tlow = 50
thigh = 150

# create mask that is black outside the desired range and white inside the desired range
mask = img.copy()
mask[mask <= tlow] = 0
mask[mask > thigh ] = 255

# modify input by 1.2 factor
result2 = img.copy()
result2 = (1.2 * result2).clip(0,255).astype(np.uint8)

# use mask to combine the input and the modified image
result2[mask==0] = 0
result2[mask==255] = 255

# method 3

# set threshold values
tlow = 50
thigh = 150

result3 = img.copy()
result3[result3 <= tlow] = 0
result3[result3 > thigh ] = 255
result3 = result3.astype(np.float32)
result3[(result3>50) & (result3<=150)] *= 1.2
result3 = result3.clip(0,255).astype(np.uint8)

# save result
cv2.imwrite("grad_process1.png", result1)
cv2.imwrite("grad_mask.png", mask)
cv2.imwrite("grad_process2.png", result2)
cv2.imwrite("grad_process3.png", result3)

# view result
cv2.imshow("result1", result1)
cv2.imshow("mask", mask)
cv2.imshow("result2", result2)
cv2.imshow("result3", result3)
cv2.waitKey(0)
cv2.destroyAllWindows()


结果 1:

结果 2:

结果 3:

而不是 50<myimg<=150 使用

(myimg>50) & (myimg<=150)

不要忘记 () 因为它不会起作用。

而且你需要=两边大小相同的数组

myimg[(myimg>50) & (myimg<=150)] = myimg[(myimg>50) & (myimg<=150)] * 1.2

或更短

myimg[(myimg>50) & (myimg<=150)] *= 1.2

示例代码

import numpy as np
import random

random.seed(0)

myimg = np.array([random.randint(0, 255) for x in range(10)], float)
print(myimg)

myimg[(myimg>50) & (myimg<=150)] = myimg[(myimg>50) & (myimg<=150)] * 1.2
#myimg[(myimg>50) & (myimg<=150)] = myimg * 1.2

print(myimg)