?
?
兄弟们,实验代码的python版本就在这了,欢迎继续改
简单阈值处理 cv2.threshold() 所谓阈值处理,就是给定一个阈值,当像素值比指定阈值大或小时做相关的操作。这个字念yu,不是fa,方法签名为:cv2.threshold(src,thresh,maxval,type,dst=None),需要将的是OpenCV中提供的几种type:
cv2.THRESH_BINARY:若像素值大于阈值,则置为maxval;否则置0 cv2.THRESH_BINARY_INV:THRESH_BINARY的反转 cv2.THRESH_TRUNC:若像素值大于阈值,则置为阈值;否则不变 cv2.THRESH_TOZERO:小于阈值的部分置为0;其他不变 cv2.THRESH_TOZERO_INV:THRESH_TOZERO的反转 ?
import cv2
import numpy as np
'''
用滑动条控制阈值处理(控制其类型和阈值)
按键操作说明:
1、键盘按键【Esc】-退出程序
2、滑动条模式0--二进制阈值
3、滑动条模式1--反二进制阈值
4、滑动条模式2--截断阈值
5、滑动条模式3--反阈值化为0
6、滑动条模式4--阈值化为0
'''
path_of_src = "E:/pycharm_work/2021_10_14/threshold/2.tif"
min_threshold = 0
max_threshold = 255
switch = "0--1--2--3--4"
def load_image(path):
src = cv2.imread(path,0)
# cv2.imshow("src",src)
# cv2.imwrite("./threshold/2.jpg", src)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
return src
def threshold(src,threshold_value,flag):
'''
2、滑动条模式0--二进制阈值
3、滑动条模式1--反二进制阈值
4、滑动条模式2--截断阈值
5、滑动条模式3--反阈值化为0
6、滑动条模式4--阈值化为0
'''
if flag == 0:
_,dst = cv2.threshold(src,threshold_value,255,0)
elif flag == 1:
_,dst = cv2.threshold(src,threshold_value,255,1)
elif flag == 2:
_,dst = cv2.threshold(src,threshold_value,255,2)
elif flag == 3:
_,dst = cv2.threshold(src,threshold_value,255,3)
else:
_,dst = cv2.threshold(src,threshold_value,255,4)
return dst
def nothing(pos):
pass
if __name__ == "__main__":
#loading the original picture
src = load_image(path_of_src)
#create one Window
cv2.namedWindow("THRESHOLD_WINDOW",0)
cv2.resizeWindow("THRESHOLD_WINDOW", 1000,600)
#cv2.imshow("src",src)
#create one Trackbar
#参数1:滑动条返回值 参数2:对应窗口 参数3:最小值 参数4:最大值 参数5:为了解决createTrackbar只能返回一个滑动条的问题
cv2.createTrackbar("The threshold value","THRESHOLD_WINDOW",min_threshold,max_threshold,nothing)
cv2.createTrackbar(switch,"THRESHOLD_WINDOW",0,4,nothing)
print("1、键盘按键【Esc】-退出程序,2、滑动条模式0--二进制阈值,3、滑动条模式1--反二进制阈值,4、滑动条模式2--截断阈值,5、滑动条模式3--反阈值化为0,6、滑动条模式4--阈值化为0")
while True:
value_of_threshold = cv2.getTrackbarPos("The threshold value","THRESHOLD_WINDOW")
flag = cv2.getTrackbarPos(switch,"THRESHOLD_WINDOW")
dst = threshold(src,value_of_threshold,flag)
cv2.imshow("THRESHOLD_WINDOW",dst)
if cv2.waitKey(1)& 0xFF == 27:
break
pass
?
|