[PYTHON] Grayscale and brightness smoothing

Execution environment

Google Colaboratory

Preparing to load images with Google Colaboratory

python


from google.colab import files
from google.colab import drive
drive.mount('/content/drive')

Loading the required libraries

python


import cv2 #opencv
import matplotlib.pyplot as plt 
%matplotlib inline
img = plt.imread("/content/drive/My Drive/Colab Notebooks/img/Lenna.bmp")
#↑ plt from this article.I decided to read it with imread.

Various conversions

python


plt.figure(figsize=(9, 6), dpi=100,
           facecolor='w', linewidth=0, edgecolor='w')

#Original image
plt.subplot(3,3,1)
plt.imshow(img)
plt.subplot(3,3,4)
color = ('b','g','r')
for i,col in enumerate(color):
    histr = cv2.calcHist([img],[i],None,[256],[0,256])
    plt.plot(histr,color = col)
    plt.xlim([0,256])

#grayscale
plt.subplot(3,3,2)
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) 
plt.imshow(gray)
plt.subplot(3,3,5)
plt.hist(gray.ravel(),256,[0,256])

#Brightness smoothing
plt.subplot(3,3,3)
dst = cv2.equalizeHist(gray)
plt.imshow(dst)
plt.subplot(3,3,6)
plt.hist(dst.ravel(),256,[0,256])

plt.show()

result

image.png

From the left Original / Grayscale / Brightness smoothing

grammar grayscale

python


cv2.cvtColor(src, cv2.COLOR_RGB2GRAY) 

Brightness smoothing

python


cv2.equalizeHist(src)

By smoothing the brightness, the histogram spreads evenly, It's easier to understand the light and dark. It seems better to do this to detect the feature.

Recommended Posts

Grayscale and brightness smoothing
Grayscale image and save as csv