[Python image processing] Sixteen. Logarithmic transformation and gamma transformation of grayscale nonlinear transformation of image

This series of articles is to explain the knowledge of Python OpenCV image processing. In the early stage, it mainly explains the introduction of images and the basic usage of OpenCV. Image recognition, image classification applications. I hope the article is helpful to you. If there are any shortcomings, please forgive me~

The previous article explained the knowledge of image grayscale processing and linear transformation, combined with OpenCV to call the cv2.cvtColor() function to realize image grayscale operation, this article mainly explains nonlinear transformation, and uses a custom method to grayscale the image processing, including logarithmic and gamma transformations. This article mainly explains the linear transformation of grayscale. I hope the basic knowledge will be helpful to you.

  • 1. Image grayscale nonlinear transformation: DB=DA×DA/255
  • 2. Image grayscale logarithmic transformation
  • 3. Image grayscale gamma transformation
  • Four. Summary

The article refers to my previous series of image processing articles and OpenCV library functions. At the same time, this article involves the basic knowledge of "Computer Graphics", please come down and add. All source code of this series on github:

  • https://github.com/eastmountyxz/ ImageProcessing-Python

I have been learning Python for nearly eight years, and I have met many bigwigs and friends, thank you. Knowing that I am good at it, I have to work hard to move forward, and there are no shortcuts in programming, so just do it. I hope that I can study and write articles more thoroughly in the future. At the same time, I am very grateful to the big guys in the references for their articles, sharing, and mutual encouragement. - https://blog.csdn.net/eastmount

1. Image grayscale nonlinear transformation: DB=DA×DA/255

The grayscale nonlinear transformation of the image mainly includes logarithmic transformation, power transformation, exponential transformation, and piecewise function transformation. The grayscale processing of the image is performed through the nonlinear relationship. The following mainly explains three common types of grayscale nonlinear transformation.

The gray value of the original image is nonlinearly transformed according to the formula DB=DA×DA/255, and the code is as follows:

# -*- coding: utf-8 -*-
import cv2  
import numpy as np  
import matplotlib.pyplot as plt

#read raw image
img = cv2.imread('miao.png')

#Image grayscale conversion
grayImage = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

#Get image height and width
height = grayImage.shape[0]
width = grayImage.shape[1]

#create an image
result = np.zeros((height, width), np.uint8)

#Image grayscale nonlinear transformation: DB=DA×DA/255
for i in range(height):
    for j in range(width):
        gray = int(grayImage[i,j])*int(grayImage[i,j]) / 255
        result[i,j] = np.uint8(gray)

#display image
cv2.imshow("Gray Image", grayImage)
cv2.imshow("Result", result)

#wait to show
cv2.waitKey(0)
cv2.destroyAllWindows()
copy

The output result of image grayscale nonlinear transformation is shown in the figure below:

2. Image grayscale logarithmic transformation

The logarithmic transformation of image grayscale is generally expressed as shown in the formula:

Where c is a scale comparison constant, DA is the gray value of the original image, and DB is the transformed target gray value. As shown in the figure below, it represents the change of gray value under the logarithmic curve.

Since the logarithmic curve has a large slope in areas with low pixel values ​​and a small slope in areas with high pixel values, the contrast of darker areas will be improved after the image is logarithmically transformed. This transformation can be used to enhance the dark details of an image, thereby expanding the darker pixels in a compressed high-value image.

The logarithmic transformation realizes the effect of extending low gray values ​​and compressing high gray values, and is widely used in the display of spectrum images. A typical application is the Fourier spectrum, whose dynamic range may be as wide as 0 to 106. When directly displaying the spectrum, the dynamic range of the image display device often cannot meet the requirements, thus losing a lot of dark details; and after using the logarithmic transformation, the image's The dynamic range is reasonably compressed non-linearly so that it can be displayed clearly. In the image below, the untransformed spectrum has been log-transformed to increase the contrast in low-gray areas, thereby enhancing the details in the shadows.

The code below implements the logarithmic transformation of the image grayscale.

# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import cv2

#draw a curve
def log_plot(c):
    x = np.arange(0, 256, 0.01)
    y = c * np.log(1 + x)
    plt.plot(x, y, 'r', linewidth=1)
    plt.rcParams['font.sans-serif']=['SimHei'] #Display Chinese labels normally
    plt.title(u'logarithmic transformation function')
    plt.xlim(0, 255), plt.ylim(0, 255)
    plt.show()

#logarithmic transformation
def log(c, img):
    output = c * np.log(1.0 + img)
    output = np.uint8(output + 0.5)
    return output

#read raw image
img = cv2.imread('test.png')

#plot logarithmic transformation curve
log_plot(42)

#Image grayscale logarithmic transformation
output = log(42, img)

#display image
cv2.imshow('Input', img)
cv2.imshow('Output', output)
cv2.waitKey(0)
cv2.destroyAllWindows()
copy

The figure below shows the effect picture after logarithmic function processing. Logarithmic transformation is better for image enhancement with low overall contrast and low gray value.

The corresponding logarithmic function curve is shown in the figure

3. Image grayscale gamma transformation

Gamma transform, also known as exponential transform or power transform, is another commonly used gray scale nonlinear transform. The gamma transformation of image grayscale is generally expressed as shown in the formula:

  • When γ>1, the image will be stretched in areas with higher gray levels and compressed with lower gray levels.
  • When γ<1, it will stretch the areas with lower gray levels in the image and compress the parts with higher gray levels.
  • When γ=1, the grayscale transformation is linear, and the original image is changed in a linear manner at this time.

Python implements the gamma transformation code of image grayscale as follows, mainly calling the power function.

# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import cv2

#draw a curve
def gamma_plot(c, v):
    x = np.arange(0, 256, 0.01)
    y = c*x**v
    plt.plot(x, y, 'r', linewidth=1)
    plt.rcParams['font.sans-serif']=['SimHei'] #Display Chinese labels normally
    plt.title(u'gamma transform function')
    plt.xlim([0, 255]), plt.ylim([0, 255])
    plt.show()

#gamma transformation
def gamma(img, c, v):
    lut = np.zeros(256, dtype=np.float32)
    for i in range(256):
        lut[i] = c * i ** v
    output_img = cv2.LUT(img, lut) #Mapping of pixel gray value
    output_img = np.uint8(output_img+0.5)  
    return output_img

#read raw image
img = cv2.imread('test.png')

#Plot the gamma transformation curve
gamma_plot(0.00000005, 4.0)

#Image grayscale gamma transformation
output = gamma(img, 0.00000005, 4.0)

#display image
cv2.imshow('Imput', img)
cv2.imshow('Output', output)
cv2.waitKey(0)
cv2.destroyAllWindows()
copy

The following figure shows the effect picture after gamma transformation processing. Gamma transformation has obvious image enhancement effect on low image contrast and high overall brightness value (or due to camera overexposure).

The corresponding power law function curve is shown in the figure.

Four. Summary

Written here, the introduction of this article is over. I hope the article is helpful to everyone. If there are any mistakes or deficiencies, please let me know. The article was written on the continuous running of the postgraduate entrance examination. I have experienced too many things. There are joys and sorrows. I need to change myself and treat my family well. I also hope that readers will cheer with me.

Thank you to the fellow travelers on the way to study, live up to the encounter, and don't forget the original intention. The moon is the circle of my hometown~

2022 is about to leave, and it will be another busy year. Thanks to the goddess for her encouragement and Xiao Luo's healing smile. December will be even busier, so hopefully all goes well. Keep the clouds open to see the bright moon, come on! After four years of Ph.D. study, I still wrote some things, from the ignorance of safety at the beginning to the ignorance of the present, I also took some notes, and I hope it will be helpful to everyone. I really don't have much time to write a blog this year, and I don't have much time to answer bloggers' questions in detail, please forgive me. When the color in the picture is lighter or even white, I tend to be busier, and more blogs and codes are shared during winter and summer vacations, projects, studies, scientific research, technology, and the most important thing is family and family relationship. Nami’s life, let’s move forward with gratitude.

I hope to graduate as soon as possible and return to my hometown Guizhou to continue to be a teacher. I feel that there are so many blogs to share, many courses to take, many open source codes to learn, and so much knowledge to learn. I look forward to the day when I stand in front of the podium again. Continue to sink your heart to study, although you cook but work hard, continue to work hard, Wanna!

(By: Nazhang House 2022-12-21 Night on Earth)

references:

  • Research on image sharpening and edge extraction technology based on Miao costumes [J]. Modern Computer, 2018(10).
  • "Digital Image Processing" (3rd edition), written by Gonzales, translated by Ruan Qiuqi, Electronic Industry Press, 2013.
  • "Digital Image Processing" (3rd edition), Ruan Qiuqi, Electronic Industry Press, 2008, Beijing.
  • "Introduction to OpenCV3 Programming", Mao Xingyun, Leng Xuefei, Electronic Industry Press, 2015.
  • Opencv learning (16) color space conversion cvtColor()
  • python+opencv+image special effects (image grayscale processing, color flipping, image fusion, edge detection, relief effect, color mapping)
  • [Digital Image Processing] 5. Detailed explanation of grayscale linear change, grayscale nonlinear change, thresholding and equalization processing of MFC image point operation

Tags: Python OpenCV

Posted by abhi201090 on Tue, 28 Feb 2023 20:21:35 +1030