如何在 OpenCV Python 中對兩個影像執行按位與運算?


按位與運算在計算機視覺或影像處理中一個非常重要的應用是建立影像的掩碼。我們還可以使用該運算子向影像新增水印。

影像的畫素值表示為 numpy ndarray。畫素值使用 8 位無符號整數 (uint8) 儲存,範圍從 0 到 255。兩個影像之間的按位與運算是在這兩個對應影像的畫素值的二進位制表示上執行的。

以下是執行按位與運算的語法:

cv2.bitwise_and(img1, img2, mask=None)

img1img2 是兩個輸入影像,mask 是掩碼操作。

步驟

要計算兩個影像之間的按位與,您可以按照以下步驟操作:

匯入所需的庫OpenCV。確保您已安裝它。

import cv2

使用cv2.imread()方法讀取影像。影像的寬度和高度必須相同。

img1 = cv2.imread('lamp.jpg')
img2 = cv2.imread('jonathan.jpg')

使用 cv2.biwise_and(img1, img2) 計算影像的按位與

and_img = cv2.bitwise_and(img1,img2)

顯示按位與影像。

cv2.imshow('Bitwise AND Image', and_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

輸入影像

我們將在下面的示例中使用以下影像作為輸入檔案。

示例 1

在下面的 Python 程式中,我們對兩個彩色影像計算按位與

# import required libraries import cv2 # read two input images. # The size of both images must be the same. img1 = cv2.imread('lamp.jpg') img2 = cv2.imread('jonathan.jpg') # compute bitwise AND on both images and_img = cv2.bitwise_and(img1,img2) # display the computed bitwise AND image cv2.imshow('Bitwise AND Image', and_img) cv2.waitKey(0) cv2.destroyAllWindows()

輸出

執行此 Python 程式時,將產生以下輸出:

示例 2

下面的 Python 程式展示了按位與運算在影像上的應用。我們建立了一個掩碼,然後用它來執行按位與運算。

# import required libraries import cv2 import matplotlib.pyplot as plt import numpy as np # Read an input image as a gray image img = cv2.imread('jonathan.jpg',0) # create a mask mask = np.zeros(img.shape[:2], np.uint8) mask[100:400, 150:600] = 255 # compute the bitwise AND using the mask masked_img = cv2.bitwise_and(img,img,mask = mask) # display the input image, mask, and the output image plt.subplot(221), plt.imshow(img, 'gray'), plt.title("Original Image") plt.subplot(222), plt.imshow(mask,'gray'), plt.title("Mask") plt.subplot(223), plt.imshow(masked_img, 'gray'), plt.title("Output Image") plt.show()

輸出

執行此 Python 程式時,將產生以下輸出:

更新於:2022-09-27

3K+ 瀏覽量

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告