Determine the threshold using the P tile method in python

Background

In a university lecture, I had a problem to find the threshold using the P tile method, so I implemented it using python3.

What is the p-tile method?

It is an algorithm that determines the point that divides the area by X% in the histogram as the threshold value.

code

 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.

reference

Binarization filter by P tile method

Recommended Posts

Determine the threshold using the P tile method in python
Try using the Wunderlist API in Python
Try using the Kraken API in Python
Tweet using the Twitter API in Python
Learn the design pattern "Template Method" in Python
Try using the BitFlyer Ligntning API in Python
I tried the least squares method in Python
To dynamically replace the next method in python
Learn the design pattern "Factory Method" in Python
Pre-process the index in Python using Solr's ScriptUpdateProcessor
Try implementing the Monte Carlo method in Python
Try using the DropBox Core API in Python
Simplex method (simplex method) in Python
Private method in python
[AWS IoT] Register things in AWS IoT using the AWS IoT Python SDK
Initial settings when using the foursquare API in python
Using the National Diet Library Search API in Python
Using the LibreOffice app in Python (1) Where are the macros?
Approximate a Bezier curve through a specified point using the least squares method in Python
Download the file in Python
Implement method chain in Python
Suppressing method overrides in Python
Translate using googletrans in Python
Using Python mode in Processing
How to use the __call__ method in a Python class
Get the MIME type in Python and determine the file format
[Python] LASSO regression with equation constraints using the multiplier method
Solve the Japanese problem when using the CSV module in Python.
I clustered the dollar yen using the k-medoids method in python and calculated the correct answer rate.
Determine the date and time format in Python and convert to Unixtime
GUI programming in Python using Appjar
Getting the arXiv API in Python
Precautions when using pit in Python
python Note: Determine if command line arguments are in the list
Python in the browser: Brython's recommendation
Save the binary file in Python
Python beginners tried Hello World in 30 seconds using the micro-framework Flask
Get the desktop path in Python
Try implementing extension method in python
Try using LevelDB in Python (plyvel)
Get the script path in Python
In the python command python points to python3.8
Implement the Singleton pattern in Python
A function that measures the processing time of a method in python
Implemented label propagation method in Python
Using global variables in python functions
Simulate Monte Carlo method in Python
Hit the web API in Python
Let's see using input in python
Infinite product in Python (using functools)
Hash method (open address method) in Python
Extract the targz file using python
Edit videos in Python using MoviePy
I wrote the queue in Python
Calculate the previous month in Python
Examine the object's class in python
Get the desktop path in Python
Try using the Python Cmd module
Get the host name in Python
Regularly upload files to Google Drive using the Google Drive API in Python
Handwriting recognition using KNN in Python