Python — OpenCV基本用法

son John
3 min readMar 27, 2020

--

  • 載入模組:
import cv2
  • 讀取圖片:
img = cv2.imread('./Images/test.jpg')#讀取為灰階圖片
img = cv2.imread('./Images/test.jpg', cv2.IMREAD_GRAYSCALE)
  • 顯示圖片:
cv2.imshow('Image title', img) #只要 Title 不一樣就會另開視窗
cv2.waitKey(0) #等待按下隨機按鍵才繼續執行,否則圖片會閃一下就消失
cv2.destroyAllWindows() #關閉所有cv2視窗
  • 圖片處理:
img2 = img + 100          #若直接ndarray相加,則數值可能會過大,而顏色錯誤
img3 = cv2.add(img, 100) #使用cv2模組則不會出錯
img4 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #轉為灰階圖片
img5 = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) #轉為 RGB 圖片
  • 提取Pixel:
#提取灰階圖座標點(100, 100)的 Pixel
#若圖片非灰階圖則產生Error
x = img.item((100, 100))
#提取彩色圖片座標點(100, 100)的第一通道(若此圖片為 BGR 則為提取B)
x1 = img.item((100, 100, 0))
  • 設置Pixel:
#設置灰階圖座標點(100, 100)的 Pixel 為200
#若圖片非灰階圖則產生Error
img.itemset((100, 100), 200)
#設置彩色圖片座標點(100, 100)的第一通道為200(若此圖片為 BGR 則為設置B)
img.itemset((100, 100, 0), 200)
  • 提取BGR:
b = img[:,:,0]
g = img[:,:,1]
r = img[:,:,2]
  • Complement(正負片轉換,即黑白對調):
cm = np.zeros(img.shape, np.uint8) + 255  #產生和 img 同等大小的255陣列
img6 = cv2.scaleAdd(img, -1, cm) #圖片處理為:y = -1 * x + 255
  • 計算 Pixel 在數值(0~255)個別的總數量:
#可為多個影像
# cv2.calcHist(影像, 通道, 遮罩, 區間數量, 數值範圍)
pixel = cv2.calcHist([img], [0], None, [256], [0, 256])
  • 畫圖表:
import matplotlib.pyplot as plt  #載入模組plt.plot(pixel)                  #畫圖
plt.xlim([0, 256]) #設置X軸座標範圍
plt.xlabel('Pixel') #設置X軸文字
plt.ylabel('Count') #設置Y軸文字
plt.show() #顯示圖表
  • 直方圖:
import matplotlib.pyplot as plt  #載入模組plt.bar([x for x in range(256)], [x[0] for x in pixel]) #畫直方圖
plt.xlim([0, 256]) #設置X軸座標範圍
plt.xlabel('Pixel') #設置X軸文字
plt.ylabel('Count') #設置Y軸文字
plt.show() #顯示圖表

--

--

No responses yet