Image processing with Python 100 knocks # 4 Binarization of Otsu (discriminant analysis method)

Introduction

Hi, I'm Ramu. We will implement Otsu's binarization (discriminant analysis method), which is a method to automatically determine the threshold value used for binarization.

Fourth: Binarization of Otsu

Binarization is the process of converting an image into a monochrome image with only two colors, black and white. After determining the threshold value, replace the pixel values below the threshold value with white and the pixels with pixel values above the threshold value with black. So far, I explained in the previous binarization. This time, we will deal with the method of automatically determining this threshold.

In Otsu's binarization, the class is divided into two according to the threshold. The threshold value when the degree of separation is maximum in these two classes is the threshold value when binarizing. The parameters required to calculate the degree of separation can be calculated by the following formula.

Separation: $ X = \ dfrac {\ sigma _ {b} ^ {2}} {\ sigma _ {w} ^ {2}} $

In-class distribution: $ \ sigma _ {b} ^ {2} = \ dfrac {\ omega _ {0} \ omega _ {1}} {(\ omega _ {0} + \ omega _ {1}) ^ 2 } (M _ {0} + M _ {1}) ^ 2 $

Distribution between classes: $ \ sigma _ {b} ^ {2} = \ omega _ {0} \ sigma _ {0} ^ {2} + \ omega _ {1} \ sigma _ {1} ^ {2} $

Number of pixels belonging to class 0,1: $ \ omega _0, \ omega _1 $

Variance of pixel values belonging to classes 0,1: $ \ sigma _0, \ sigma _1 $

Average pixel values belonging to classes 0,1: $ M_0, M_1 $

Average pixel value of the entire image: $ M $

Total pixel values belonging to class 0,1: $ P_0, P_1 $

In summary, when the threshold is 0 to 255, the degree of separation should be calculated 256 times to find the threshold value that maximizes the degree of separation.

otsuBinarization.py


import numpy as np
import cv2
import matplotlib.pyplot as plt
# from statistics import variance
import statistics as st
plt.gray()


def otsuBinarization(img):
  #Image copy
  dst = img.copy()
  #Grayscale
  gray = cv2.cvtColor(dst, cv2.COLOR_BGR2GRAY)

  w,h = gray.shape
  Max = 0

  #Average pixel value of the entire image
  M = np.mean(gray)

  #Applies to all 256 threshold values
  for th in range(256):
    #Classification
    g0,g1 = gray[gray<th],gray[gray>=th]

    #Number of pixels
    w0,w1 = len(g0),len(g1)
    #Pixel value distribution
    s0_2,s1_2 = g0.var(),g1.var()
    #Pixel value average
    m0,m1 = g0.mean(),g1.mean()
    #Pixel value total
    p0,p1 = g0.sum(),g1.sum()

    #In-class distribution
    sw_2 = w0*s0_2 + w1*s1_2
    #Distribution between classes
    sb_2 = ((w0*w1) / ((w0+w1)*(w0+w1))) * ((m0-m1)*(m0-m1))
    #Separation
    if (sb_2 != 0):
      X = sb_2 / sw_2
    else:
      X = 0

    if (Max < X):
      Max = X
      t = th

  #Binarization
  idx = np.where(gray < t)
  gray[idx] = 0
  idx = np.where(gray >= t)
  gray[idx] = 255

  return gray


#Image reading
img = cv2.imread('image.jpg')

#Binarization of Otsu
mono = otsuBinarization(img)

#Save image
cv2.imwrite('result.jpg', mono)
#Image display
plt.imshow(mono)
plt.show()

ファイル名 ファイル名 ファイル名

The left image is the input image, the center of the image is the output image when the threshold is manually set to 128, and the right image is the output image this time. Even if the threshold value is automatically determined and binarized, the image is output without much discomfort. As an aside, my implementation doesn't use the average pixel value M for the entire image.

in conclusion

If you have any questions, please feel free to contact us. imori_imori's Github has the official answer, so please check that as well. .. Also, since python is a beginner, please kindly watch over and comment on any mistakes.

Recommended Posts

Image processing with Python 100 knocks # 4 Binarization of Otsu (discriminant analysis method)
Image processing with Python 100 knocks # 3 Binarization
Image processing with Python 100 knocks # 2 Grayscale
Basics of binarized image processing with Python
Image processing with Python 100 knocks # 8 Max pooling
Drawing with Matrix-Reinventor of Python Image Processing-
Image processing with Python 100 knocks # 7 Average pooling
Image processing with Python 100 knocks # 9 Gaussian filter
Image processing with Python
Image processing with Python (Part 2)
[OpenCV / Python] I tried image analysis of cells with OpenCV
[Chapter 5] Introduction to Python with 100 knocks of language processing
Image processing with Python (Part 1)
[Chapter 3] Introduction to Python with 100 knocks of language processing
Image processing with Python (Part 3)
[Chapter 2] Introduction to Python with 100 knocks of language processing
[Chapter 4] Introduction to Python with 100 knocks of language processing
[Python] Image processing with scikit-image
3. Natural language processing with Python 5-1. Concept of sentiment analysis [AFINN-111]
Image binarization using linear discriminant analysis
Image processing with Python 100 knock # 10 median filter
Grayscale by matrix-Reinventor of Python image processing-
Image processing with Python & OpenCV [Tone Curve]
Image processing with Python 100 knock # 12 motion filter
Easy image processing in Python with Pillow
Analysis of X-ray microtomography image by Python
Light image processing with Python x OpenCV
Matrix Convolution Filtering-Reinventor of Python Image Processing-
python image processing
Image processing 100 knocks ①
Getting started with Python with 100 knocks on language processing
Image processing from scratch with python (5) Fourier transform
[Various image analysis with plotly] Dynamic visualization with plotly [python, image]
Medical image analysis with Python 1 (Read MRI image with SimpleITK)
Image processing from scratch with python (4) Contour extraction
Image processing? The story of starting Python for
Image Processing with Python Environment Setup for Windows
Static analysis of Python code with GitLab CI
Python practice data analysis Summary of learning that I hit about 10 with 100 knocks
[Language processing 100 knocks 2020] Summary of answer examples by Python
Image processing with MyHDL
Extract the table of image files with OneDrive & Python
Image processing by matrix Basics & Table of Contents-Reinventor of Python image processing-
Binarization with OpenCV / Python
Notes on HDR and RAW image processing with Python
Kernel Method with Python
First Python image processing
Destroy the intermediate expression of the sweep method with Python
Voice analysis with python
[Chapter 6] Introduction to scikit-learn with 100 knocks of language processing
Calculate the regression coefficient of simple regression analysis with python
3. Natural language processing with Python 4-1. Analysis for words with KWIC
Challenge principal component analysis of text data with Python
Planar skeleton analysis with Python (4) Handling of forced displacement
Image processing with Python (I tried binarizing it into a mosaic art of 0 and 1)
Voice analysis with python
Data analysis with Python
Various processing of Python
Image Processing with PIL
3. Natural language processing with Python 5-5. Emotion value analysis of Japanese sentences [Japanese evaluation polarity dictionary (words)]
3. Natural language processing with Python 5-3. Emotion value analysis of Japanese sentences [Word emotion polarity value correspondence table]