当前位置: 移动技术网 > IT编程>脚本编程>Python > python+opencv实现阈值分割

python+opencv实现阈值分割

2019年01月04日  | 移动技术网IT编程  | 我要评论

济州岛娱乐89168澳门官方,岑文本初仕萧铣,道葬

最近老师留了几个作业,虽然用opencv很简单一句话就出来了,但是还没用python写过。在官方文档中的tutorial中的threshold里,看到可以创建两个滑动条来选择type和value,决定用python实现一下

注意python中的全局变量,用global声明

开始出现了一些问题,因为毁掉函数每次只能传回一个值,所以每次只能更新value,后来就弄了两个毁掉函数,这个时候,又出现了滑动其中一个,另一个的值就会变为默认值的情况,这个时候猜想是全局变量的问题,根据猜想改动之后果然是。
感觉还有更简单的方法,不需要设置两个回调参数,对python不是很熟悉,时间有限,先不折腾了


(2016-5-10)到opencv-python tutorials's documentation!可以下载

代码

# -*- coding: utf-8 -*- 

import cv2

#两个回调函数
def thresholdtype(threshold_type):
 global threshold_type 
 threshold_type = threshold_type
 print threshold_type, threshold_value
 ret, dst = cv2.threshold(scr, threshold_value, max_value, threshold_type) 
 cv2.imshow(window_name,dst)

def thresholdvalue(threshold_value):
 global threshold_value
 threshold_value = threshold_value
 print threshold_type, threshold_value
 ret, dst = cv2.threshold(scr, threshold_value, max_value, threshold_type) 
 cv2.imshow(window_name,dst)

#全局变量
"""
"type: 
0: binary 
1: binary inverted 
2: truncate 
3: to zero 
4: to zero inverted"
"""
threshold_value = 0
threshold_type = 3
max_value = 255
max_type = 4
max_binary_value = 255
window_name = "threshold demo"
trackbar_type = "type"
trackbar_value = "value"

#读入图片,模式为灰度图,创建窗口
scr = cv2.imread("g:\homework\smalltarget.png",0)
cv2.namedwindow(window_name)

#创建滑动条
cv2.createtrackbar( trackbar_type, window_name, \
   threshold_type, max_type, thresholdtype)
cv2.createtrackbar( trackbar_value, window_name, \
   threshold_value, max_value, thresholdvalue )
#初始化
thresholdtype(0)

if cv2.waitkey(0) == 27: 
 cv2.destroyallwindows()

执行

import threshold
>>> reload(threshold)
0 0
2 0
1 0
1 1
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 10
1 12
1 13
1 16
1 18

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网