# Python如何实现图像强度转换操作？

## 本文概述

1. 图像负片(线性)
2. 对数转换
3. 幂律(Gamma)变换
4. 分段线性变换函数

T是f在点(x, y)的邻域上的算子

## 对数转换–

``````import cv2
import numpy as np

# Open the image.

# Apply log transform.
c = 255 /(np.log( 1 + np. max (img)))
log_transformed = c * np.log( 1 + img)

# Specify the data type.
log_transformed = np.array(log_transformed, dtype = np.uint8)

# Save the output.
cv2.imwrite( 'log_transformed.jpg' , log_transformed)``````

## 幂法(伽马)变换–

。伽玛校正对于在屏幕上正确显示图像非常重要, 以防止从具有不同显示设置的不同类型的显示器观看图像时图像变白或变暗。这样做是因为我们的眼睛以伽马形曲线感知图像, 而相机则以线性方式捕获图像。以下是应用伽玛校正的Python代码。

``````import cv2
import numpy as np

# Open the image.

# Trying 4 gamma values.
for gamma in [ 0.1 , 0.5 , 1.2 , 2.2 ]:

# Apply gamma correction.
gamma_corrected = np.array( 255 * (img /255 ) * * gamma, dtype = 'uint8' )

# Save edited images.
cv2.imwrite( 'gamma_transformed' + str (gamma) + '.jpg' , gamma_corrected)``````

## 分段线性变换函数–

``Contrast =  (I_max - I_min)/(I_max + I_min)``

``````import cv2
import numpy as np

# Function to map each intensity level to output intensity level.
def pixelVal(pix, r1, s1, r2, s2):
if ( 0 <= pix and pix <= r1):
return (s1 /r1) * pix
elif (r1 <pix and pix <= r2):
return ((s2 - s1) /(r2 - r1)) * (pix - r1) + s1
else :
return (( 255 - s2) /( 255 - r2)) * (pix - r2) + s2

# Open the image.

# Define parameters.
r1 = 70
s1 = 0
r2 = 140
s2 = 255

# Vectorize the function to apply it to each value in the Numpy array.
pixelVal_vec = np.vectorize(pixelVal)

# Apply contrast stretching.
contrast_stretched = pixelVal_vec(img, r1, s1, r2, s2)

# Save edited image.
cv2.imwrite( 'contrast_stretch.jpg' , contrast_stretched)``````

• 回顶