求取差值圖像時,解決兩個圖像相減,差值圖像結果限定在[0,255]範圍內問題

這是因爲當我們使用imread函數直接去加載圖像時,讀取的圖像格式是 CV_8UC3 即爲uint8 是unsigned 的,因此在圖像相減過程中會自動將像素值限定在[0,255]範圍內。假設img1中像素值爲(12,3,255),img2像素值爲(13,4,23),則img1-img2的像素值爲(255,255,232),但是我們實際上是需要(-1,-1, 232)。爲了解決這個問題,我們可以在讀取圖片時,將圖片的格式改爲int32的形式,這樣就可以讓負數不直接變爲0。下面對應兩種相減方式,以及其對應的效果。爲了更好的體現差值圖像的效果,我們對差值圖像還做了歸一化的操作。

img1

                  img1                                                       img2

 

一、直接相減,及其差值圖像

def grey_scale(img_gray ):
//歸一化函數
    rows, cols = img_gray.shape
    flat_gray = img_gray.reshape((cols * rows,)).tolist()
    A = min(flat_gray)
    B = max(flat_gray)
    print('A = %d,B = %d' % (A, B))
    output = np.uint8(255 / (B - A) * (img_gray - A) + 0.5)
    return output

img_1=cv2.imread("C:\\Users\\ASUS\\Desktop\\image_lib\\house.png",0)
img_2=cv2.imread("C:\\Users\\ASUS\\Desktop\\image_lib\house_256_20.png",0)
img=img_1-img_2
result=grey_scale(img) //圖片歸一化
cv2.imwrite("C:\\Users\\ASUS\\Desktop\\9c.jpg",result)

 

二、讀取時改變圖像類型,再相減操作

def grey_scale(img_gray ):
    //歸一化函數
    rows, cols = img_gray.shape
    flat_gray = img_gray.reshape((cols * rows,)).tolist()
    A = min(flat_gray)
    B = max(flat_gray)
    print('A = %d,B = %d' % (A, B))
    output = np.uint8(255 / (B - A) * (img_gray - A) + 0.5)
    return output


img_1=cv2.imread("C:\\Users\\ASUS\\Desktop\\image_lib\\house.png",0).astype(np.int32)
img_2=cv2.imread("C:\\Users\\ASUS\\Desktop\\image_lib\house_256_20.png",0).astype(np.int32)
img=img_1-img_2
result=grey_scale(img) //歸一化操作
cv2.imwrite("C:\\Users\\ASUS\\Desktop\\9c.jpg",result)

 

差值圖像

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章