Threshold.py 2.16 KB
import cv2
import numpy as np
from matplotlib import pyplot as plt

def ThresholdEverything(img):
	ret,th1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
	th2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,2)
	th3 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2)
	titles = ['Original Image', 'Global Thresholding (v = 127)',
	'Adaptive Mean Thresholding', 'Adaptive Gaussian Thresholding']
	images = [img, th1, th2, th3]
	for i in xrange(4):
		plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')
		plt.title(titles[i])
		plt.xticks([]),plt.yticks([])
	plt.show()
	return images

def GlobalThresholding(img):
	ret,th1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
	plt.plot(), plt.imshow(th1, 'gray')
	plt.title('Global Thresholding (v = 127)')
	plt.show()
	return th1

def AdaptiveMeanThresholding(img):
	th2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,2)
	plt.plot(), plt.imshow(th2, 'gray')
	plt.title('Adaptive Mean Thresholding')
	plt.show()
	return th2

def AdaptiveGaussianThresholding(img):
	th3 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2)
	plt.plot(), plt.imshow(th3, 'gray')
	plt.title('Adaptive Gaussian Thresholding')
	plt.show()
	return th3

def ThresholdChoiceProcessing(img, choice):
	if choice == '1':
		img = GlobalThresholding(img)
		return img
	elif choice == '2':
		img = AdaptiveMeanThresholding(img)
		return img
	elif choice == '3':
		img = AdaptiveGaussianThresholding(img)
		return img
	elif choice == '4':
		img = ThresholdEverything(img)
		return img
	else:
		return


def ThresholdChoice() :
	image = None
	print('\t\tThreshold Menu\n')
	while (image is None):
		image = str(raw_input('\tImage to use? By default couleur.png \n'))
		if not image:
			image = 'couleur.png'
		image = cv2.imread(str(image), 0)
	img = cv2.medianBlur(image,5)
	print ('\t1. Global Thresholding\n\t2. Adaptive Mean Thresholding\n\t3. Adaptive Gaussian Thresholding\n\t4. Everything\n')
	choice = raw_input('\n\tMultiple choices possible\n')
	for i in range (0, len(choice)):
		img = image.copy()
		img = ThresholdChoiceProcessing(img, choice[i])
	return