繁体   English   中英

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() 

而不是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)

这里有三种可能的方法来做到这一点。

第一个简单地将图像乘以因子 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:

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM