- OpenCV Python 教程
- OpenCV Python - 首頁
- OpenCV Python - 概述
- OpenCV Python - 環境配置
- OpenCV Python - 讀取影像
- OpenCV Python - 寫入影像
- OpenCV Python - 使用 Matplotlib
- OpenCV Python - 影像屬性
- OpenCV Python - 位運算
- OpenCV Python - 形狀和文字
- OpenCV Python - 滑鼠事件
- OpenCV Python - 新增軌跡條
- OpenCV Python - 縮放和旋轉
- OpenCV Python - 影像閾值化
- OpenCV Python - 影像濾波
- OpenCV Python - 邊緣檢測
- OpenCV Python - 直方圖
- OpenCV Python - 顏色空間
- OpenCV Python - 影像變換
- OpenCV Python - 影像輪廓
- OpenCV Python - 模板匹配
- OpenCV Python - 影像金字塔
- OpenCV Python - 影像加法
- OpenCV Python - 影像混合
- OpenCV Python - 傅立葉變換
- OpenCV Python - 捕捉影片
- OpenCV Python - 播放影片
- OpenCV Python - 從影片中提取影像
- OpenCV Python - 從影像生成影片
- OpenCV Python - 人臉檢測
- OpenCV Python - 均值漂移/CamShift
- OpenCV Python - 特徵檢測
- OpenCV Python - 特徵匹配
- OpenCV Python - 數字識別
- OpenCV Python 資源
- OpenCV Python - 快速指南
- OpenCV Python - 資源
- OpenCV Python - 討論
OpenCV Python - 位運算
位運算用於影像處理以及提取影像中的重要部分。
OpenCV 中實現了以下運算子:
- bitwise_and (按位與)
- bitwise_or (按位或)
- bitwise_xor (按位異或)
- bitwise_not (按位非)
示例 1
為了演示這些運算子的使用,我們使用了包含實心圓和空心圓的兩張影像。
下面的程式演示瞭如何在 OpenCV-Python 中使用位運算子:
import cv2
import numpy as np
img1 = cv2.imread('a.png')
img2 = cv2.imread('b.png')
dest1 = cv2.bitwise_and(img2, img1, mask = None)
dest2 = cv2.bitwise_or(img2, img1, mask = None)
dest3 = cv2.bitwise_xor(img1, img2, mask = None)
cv2.imshow('A', img1)
cv2.imshow('B', img2)
cv2.imshow('AND', dest1)
cv2.imshow('OR', dest2)
cv2.imshow('XOR', dest3)
cv2.imshow('NOT A', cv2.bitwise_not(img1))
cv2.imshow('NOT B', cv2.bitwise_not(img2))
if cv2.waitKey(0) & 0xff == 27:
cv2.destroyAllWindows()
輸出
示例 2
在另一個涉及位運算的示例中,OpenCV 徽標疊加在另一張影像上。在這裡,我們透過呼叫threshold()函式在徽標上獲得一個掩碼陣列,並在它們之間執行 AND 運算。
同樣,透過 NOT 運算,我們得到一個反向掩碼。並且,我們與背景影像進行 AND 運算。
以下是確定位運算子用法的程式:
import cv2 as cv
import numpy as np
img1 = cv.imread('lena.jpg')
img2 = cv.imread('whitelogo.png')
rows,cols,channels = img2.shape
roi = img1[0:rows, 0:cols]
img2gray = cv.cvtColor(img2,cv.COLOR_BGR2GRAY)
ret, mask = cv.threshold(img2gray, 10, 255, cv.THRESH_BINARY)
mask_inv = cv.bitwise_not(mask)
# Now black-out the area of logo
img1_bg = cv.bitwise_and(roi,roi,mask = mask_inv)
# Take only region of logo from logo image.
img2_fg = cv.bitwise_and(img2,img2,mask = mask)
# Put logo in ROI
dst = cv.add(img2_fg, img1_bg)
img1[0:rows, 0:cols ] = dst
cv.imshow(Result,img1)
cv.waitKey(0)
cv.destroyAllWindows()
輸出
帶掩碼的影像得到以下結果:
廣告