使用Python和OpenCV進行影像負變換


影像亮度反轉後的影像稱為負片影像,其中影像的亮部顯示為暗色,暗部顯示為亮色。彩色影像(RGB影像)的負變換將反轉,紅色區域顯示為青色,綠色區域顯示為品紅,藍色區域顯示為黃色。

在醫學影像、遙感和其他一些應用中,負變換被廣泛使用。它也有助於找到影像較暗區域的細節。

負變換函式為:

眾所周知,8點陣圖像的最大強度值為255,因此我們需要從每個畫素中減去255(最大強度值)以生成負片影像。

s = T(r) = L – 1 – r

在本文中,我們將學習使用OpenCV Python以不同方式獲得影像的負變換。

使用cv2.bitwise_not()函式

該函式計算輸入陣列的按位反轉。以下是not()函式的語法:

cv2.bitwise_not(src[, dst[, mask]])

引數

  • src:輸入影像陣列。

  • dst:與輸入陣列大小和型別相同的輸出陣列(可選)。

  • mask:可選引數。

示例

在這個例子中,我們將反轉影像陣列的每個值以獲得負片影像。

import cv2
 
# Load the image
img = cv2.imread('Images/Fruits.jpg')
 
# Invert the image using cv2.bitwise_not
img_neg = cv2.bitwise_not(img)
 
# Show the image
cv2.imshow('negative',img_neg)
cv2.waitKey(0)

輸入影像

輸出影像

使用減法

在這種方法中,我們使用兩個for迴圈(基於影像尺寸)遍歷畫素,並從每個畫素的最大畫素值(255)中減去紅色、綠色和藍色的值。

示例

讓我們實現一個不使用任何函式的彩色影像負變換。

import cv2
 
# Load the image
img = cv2.imread('Images/Fruits.jpg', cv2.COLOR_BGR2RGB)

height, width, _ = img.shape
  
for i in range(0, height - 1):
   for j in range(0, width - 1):
      # each pixel has RGB channle data 
      pixel = img[i, j]
      
      # red
      pixel[0] = 255 - pixel[0]
      
      # green
      pixel[1] = 255 - pixel[1]
      
      # blue
      pixel[2] = 255 - pixel[2]
      
      # Store new values in the pixel
      img[i, j] = pixel
        
# Display the negative transformed image
cv2.imshow('negative image', img)
cv2.waitKey(0)

輸出影像

我們已成功將彩色影像轉換為負片。最初,我們使用for迴圈迭代了影像陣列的所有值(畫素資料),然後從最大畫素值(255)中減去每個畫素值以獲得負變換影像。

示例

在這裡,我們將直接對最大強度值和影像陣列之間應用減法運算,而不是迴圈遍歷每個畫素。

import numpy as np
import cv2

img = cv2.imread('Images/Fruits.jpg')

# Subtract the img array values from max value(calculated from dtype)
img_neg = 255 - img

# Show the negative image
cv2.imshow('negative',img_neg)
cv2.waitKey(0)

輸出

對於灰度影像

對於灰度影像,在負變換中,影像的亮部顯示為暗色,暗部顯示為亮色。

示例

在這個例子中,我們將以灰度模式讀取影像以生成其負片。

import cv2
 
# Load the image
gray = cv2.imread('Images/Fruits.jpg', 0)
 
cv2.imshow('Gray image:', gray)

# Invert the image using cv2.bitwise_not
gray_neg = cv2.bitwise_not(gray)
 
# Show the image
cv2.imshow('negative',gray_neg)
cv2.waitKey(0)

輸入影像

輸出影像

我們已經學習了使用OpenCV Python獲得影像負變換的不同方法。

更新於:2023年5月31日

2K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告