光照不均勻處理——圖像的光補償


對側方向光源導致的光照不均勻進行光補償


注:使用的例子為左側方向打光

待處理圖像:

      

 

 

 目標:實現圖像二值化,不能缺少圖像信息

一、擬合光照輪廓

  1.對圖像整體進行大津閾值分割   

import cv2
import numpy as np
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False

S = cv2.imread('rice3.bmp',0)

position = np.array([],dtype = [('y',int),('x',int)])
thres, Out1 = cv2.threshold(S, 0, 255, cv2.THRESH_OTSU) #大津閾值分割
plt.imshow(Out1,'gray'), plt.title(f'閾值 = {thres}'), plt.show()

      可以看到右側亮度不夠,且輪廓接近二次曲線

 

    2.擬合光照輪廓    

#擬合光照輪廓
for i in range(S.shape[0]):   #行掃描
    flag = 0
    for j in range( S.shape[1]-1, 350, -1 ):  #從右往左進行列掃描
        if Out1[i,j] == 255 and flag == 0 :
            flag = 1
            position = np.insert(position,len(position),(i,j))
            
plt.plot(position['x'],position['y'],'*')            
coef = np.polyfit(position['y'],position['x'],2)
x_fit = np.polyval(coef, position['y'])
plt.plot(x_fit,position['y'] )

      

 

 二、生成光補償數組  

#生成光補償數組
def posi(a1,a2):
    for i,j in zip( a1, a2 ):
        yield (i,j)

comp = np.zeros(S.shape,np.float)
for i,j in posi( x_fit, position['y'] ):
    for col in range( int(i)-200, S.shape[1] ):
        comp[j, col] =  min(comp[j, col-1] + 0.09, 255)
plt.imshow(comp, 'gray'), plt.title('補償數組圖像'), plt.show()

      

 

 三、對原圖像進行光補償,並重新閾值分割

S_new = np.uint8( S + comp )  #補償原圖像
cv2.imwrite('rice_new.bmp',S_new)

thres2, Out2 = cv2.threshold(S_new, 0, 255, cv2.THRESH_OTSU) #對補償后的圖像大津閾值分割
plt.imshow(Out2,'gray'), plt.title(f'閾值 = {thres2}')
cv2.imwrite(f'rice_binary({thres2}).bmp',Out2)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM