python+opencv实现阈值分割

yipeiwu_com6年前Python基础

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

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

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

python+opencv实现高斯平滑滤波
python+opencv实现霍夫变换检测直线

(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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

浅谈python 中类属性共享的问题

感觉这种理解有问题,举个例子来说。 class Dog(object): name = 'dog' def init(self): self.age...

python批量提交沙箱问题实例

本文实例讲述了python批量提交沙箱问题,分享给大家供大家参考。具体方法如下: 出现的问题如下: 1. Popen的使用,在linux下参数用列表传,不要用字符串传 &nbs...

python DataFrame转dict字典过程详解

python DataFrame转dict字典过程详解

这篇文章主要介绍了python DataFrame转dict字典过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 背景:将商品i...

python 寻找离散序列极值点的方法

使用 scipy.signal 的 argrelextrema 函数(API),简单方便 import numpy as np import pylab as pl import...

python中pip的安装与使用教程

python中pip的安装与使用教程

在安装pip前,请确认win系统中已经安装好了python,和easy_install工具,如果系统安装成功,easy_install在目录python的安装盘(如C盘):\Python...