【OpenCV快速入門系列01】基礎操作

1 畫圖

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

def show(image):
    plt.imshow(image)
    plt.axis('off')
    plt.show()
img=np.zeros((300,300,3),dtype='uint8')
# 畫線
cv2.line(img,(0,0),(300,300),(0,255,0)) # 起點,終點,顏色
show(img)

在這裏插入圖片描述

# 畫矩形
cv2.rectangle(img,(0,0),(100,100),(255,0,0),2) # 起點,終點,顏色,線寬
show(img)

在這裏插入圖片描述

# 填充矩形
cv2.rectangle(img,(0,0),(100,100),(255,0,0),-1)
show(img)

在這裏插入圖片描述

# 畫圓
cv2.circle(img,(150,150), 50, (0,0,255), 2) # 起點,半徑,顏色,線寬
show(img)

在這裏插入圖片描述

2 翻轉

img_flip1=cv2.flip(img,1) # 水平翻轉
show(img_flip1)

在這裏插入圖片描述

img_flip0=cv2.flip(img,0) # 垂直翻轉
show(img_flip0)

在這裏插入圖片描述

img_flip=cv2.flip(img,-1) # 水平+垂直翻轉
show(img_flip)

在這裏插入圖片描述

3 裁剪

img_crop=img[0:200,0:100] # 裁剪(h,w)
show(img_crop)

在這裏插入圖片描述

4 算術操作

M = np.ones(img.shape, dtype='uint8')*100
img_add=cv2.add(img,M) # 所有像素加100
show(img_add)

在這裏插入圖片描述

img_subtract=cv2.subtract(img,M) # 所有像素減100
show(img_subtract)

在這裏插入圖片描述

5 位操作

circle = np.zeros((300,300,3), dtype='uint8')
cv2.circle(circle, (150,150), 50, (255,255,255), -1)
show(circle)

在這裏插入圖片描述

img_bit_and=cv2.bitwise_and(img,circle) # 與操作,有黑就變黑
show(img_bit_and)

在這裏插入圖片描述

img_bit_or=cv2.bitwise_or(img,circle) # 或操作,有白就變白
show(img_bit_or)

在這裏插入圖片描述

img_bit_xor=cv2.bitwise_xor(img,circle) # 異或操作,黑白變白,黑黑和白白變黑
show(img_bit_xor)

在這裏插入圖片描述

img_bit_not=cv2.bitwise_not(img) # 取反
show(img_bit_not)

在這裏插入圖片描述

6 遮擋

mask = np.zeros(img.shape,dtype='uint8') # 創建遮擋
cv2.rectangle(mask, (0,0), (100,100), (255,255,255), -1)
show(mask)

在這裏插入圖片描述

img_mask=cv2.bitwise_and(img,mask) # 對圖像遮擋
show(img_mask)

在這裏插入圖片描述

7 切分合並通道

(R,G,B)=cv2.split(img) # 切分通道
print(R.shape)
print(G.shape)
print(B.shape)

(300, 300)
(300, 300)
(300, 300)

img_merge=cv2.merge([R,G,B]) # 合併通道
show(img_merge)

在這裏插入圖片描述

8 金字塔

img_pyrdown=cv2.pyrDown(img) # 高斯金字塔下采樣,一次邊長減半
print(img_pyrdown.shape)
show(img_pyrdown)

(150, 150, 3)
在這裏插入圖片描述

img_pyrup=cv2.pyrUp(img) # 高斯金字塔上採樣,一次邊長翻倍
print(img_pyrup.shape)
show(img_pyrup)

(600, 600, 3)
在這裏插入圖片描述

down_img1 = cv2.pyrDown(img)
down_img2 = cv2.pyrDown(down_img1)
up_img = cv2.pyrUp(down_img2)
laplacian = down_img1-up_img # 拉普拉斯金字塔,邊界圖
show(laplacian)

在這裏插入圖片描述

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