In a university lecture, I had a problem to find the threshold using the P tile method, so I implemented it using python3.
It is an algorithm that determines the point that divides the area by X% in the histogram as the threshold value.
 ptile.ipynb
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
file = "./sample.png "
#Function that returns a threshold
def decideTh(area, ret):
#Threshold
th = 0
#background
background = 0
#Area ratio
bg_ratio = 1 / 2
count = 0
#Seeking background
for i in ret[0]:
background += i
if background == 0:
ratio = 0
else:
ratio = background /area
#Substitute the brightness value until the background exceeds the area ratio
if ratio <= bg_ratio:
th = ret[1][count]
count+=1
return th
#A function that converts an image as a histogram and as a threshold
def binari(filename):
#Histogram area
area = 0
#Convert the image to grayscale and assign the brightness value to the function
img = np.array(Image.open(filename).convert("L")).reshape(-1,1)
#Convert the brightness value to a histogram and substitute
ret = (plt.hist(img, bins=255))
#Find the area of the histogram
for i in ret[0]:
area += i
th = decideTh(area,ret)
return th
print(binari(file))
img = np.array(Image.open(filename).convert("L")).reshape(-1,1)
ret = (plt.hist(img, bins=255))
For this code, I quote @ seigot's Display histogram of image brightness value in python.
Recommended Posts