影像變換
-
影像放大
import cv2
import matplotlib.pyplot as plt
img = cv2.imread("images/logo.jpg")
plt.imshow(img)

輸出影像大小:
height,width,channel = img.shape
print(height,width,channel)
![]()
放大影像:
resized_img = cv2.resize(img,(width*2,height*2),interpolation=cv2.INTER_LINEAR)#放大一倍
plt.imshow(resized_img)
print(resized_img.shape)#列印影像大小
-
影像縮小
small_img = cv2.resize(img,None,fx=0.5,fy=0.5,interpolation=cv2.INTER_LINEAR)
plt.imshow(small_img)
print(small_img.shape)

cv2.resize(src, size, fx, fy, interpolation)
src:原始圖片
size:輸出影像的大小
fx:水平方向的縮放比例
fy:垂直方向的縮放比例
interpolation:插值方式
插值方式有:
cv2.INTER_NEAREST : 最臨近插值
cv2.INTER_LINEAR : 雙線性插值(默認方式)
cv2.INTER_CUBIC : 三次樣條插值
cv2.INTER_AREA : 區域插值
-
影像平移
import numpy as np
height,width = img.shape[:2]
M1 = np.float32([[1,0,100],[0,1,100]])#平移矩陣,100影像向右移動100個像素,向下移動100個像素
move_img = cv2.warpAffine(img,M1,(width,height))
plt.imshow(move_img)

-
影像旋轉
height,width = img.shape[:2]
center = (width // 2.0,height // 2.0)#旋轉的中心
M2 = cv2.getRotationMatrix2D(center,180,1)#180為逆時針旋轉180°,1表示影像旋轉程序中沒有縮放
rotation_img = cv2.warpAffine(img,M2,(width,height))
plt.imshow(rotation_img)

-
影像仿射變換
p1 = np.float32([[120,35],[215,45],[135,120]])
p2 = np.float32([[135,45],[300,110],[130,230]])
M3 = cv2.getAffineTransform(p1,p2)#計算一個變換矩陣
trans_img = cv2.warpAffine(img,M3,(width,height))
plt.imshow(trans_img)

-
影像的裁剪
crop_img = img[50:250,100:300]
plt.imshow(crop_img)


原圖 裁剪后
-
影像的位運算
與運算:(01:0,10:0,00:0,11:1)
先創建兩幅圖片:
rectangle = np.zeros((300,300),dtype='uint8')#創建一張300*300的畫布
#左上角坐標(25,25)右下角坐標(275,275)顏色255,線條-1
rect_img = cv2.rectangle(rectangle,(25,25),(275,275),255,-1)
plt.imshow(rectangle)

rectangle = np.zeros((300,300),dtype="uint8")#創建一張300*300的畫布
#圓心坐標(150,150)半徑150,顏色255,線條-1
circle_img = cv2.circle(rectangle,(150,150),150,255,-1)
plt.imshow(circle_img)

and_img = cv2.bitwise_and(rect_img,circle_img)
plt.imshow(and_img)

或運算:(01:1,10:1,11:1,00:0)
or_img = cv2.bitwise_or(rect_img,circle_img)
plt.imshow(or_img)

異或運算:(01:1,10:1,00:0,11:0)
xor_img = cv2.bitwise_xor(rect_img,circle_img)
plt.imshow(xor_img)

-
影像的分離和融合
分離:
(B,G,R)=cv2.split(img)#分離
plt.imshow(B)#藍色

(B,G,R)=cv2.split(img)#分離
plt.imshow(G)#綠色

(B,G,R)=cv2.split(img)#分離
plt.imshow(R)#紅色
融合:
zeros = np.zeros(img.shape[:2],dtype="uint8")
plt.imshow(cv2.merge([B,zeros,zeros]))

zeros = np.zeros(img.shape[:2],dtype="uint8")
plt.imshow(cv2.merge([zeros,G,zeros]))

zeros = np.zeros(img.shape[:2],dtype="uint8")
plt.imshow(cv2.merge([zeros,zeros,R]))

-
顏色空間color space
灰度:
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
plt.imshow(gray)

HSV(色度、飽和度、純度):
hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
plt.imshow(hsv)

lab:
lab = cv2.cvtColor(img,cv2.COLOR_BGR2LAB)
plt.imshow(lab)

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/292811.html
標籤:其他
上一篇:從0到1帶你實作掃雷!
下一篇:Opencv常見資料型別(一)
