彩色圖像轉灰階
1.1 程式碼
import cv2
# 顯示圖檔
def show_img(name, img):
cv2.imshow(name, img)
cv2.waitKey(0)
image_path = './over_brain.jpg'
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
image = cv2.resize(image, (250, 250))
show_img('gray1', image)
import cv2
# 顯示圖檔
def show_img(name, img):
cv2.imshow(name, img)
cv2.waitKey(0)
image_path = './over_brain.jpg'
image = cv2.imread(image_path)
image = cv2.resize(image, (250, 250))
show_img('origin', image)
image1 = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
show_img('gray2', image1)
1.2 執行結果
彩色圖像二值化
2.1 程式碼
import cv2
# 顯示圖檔
def show_img(name, img):
cv2.imshow(name, img)
cv2.waitKey(0)
image_path = './over_brain.jpg'
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
image = cv2.resize(image, (280, 280))
show_img('gray1', image)
ret1,mask1 = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)
show_img('BINARY', mask1)
ret2,mask2 = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY_INV)
show_img('BINARY_INV', mask2)
ret3,mask3 = cv2.threshold(image, 127, 255, cv2.THRESH_TRUNC)
show_img('TRUNC', mask3)
ret4,mask4 = cv2.threshold(image, 127, 255, cv2.THRESH_TOZERO)
show_img('TOZERO', mask4)
ret5,mask5 = cv2.threshold(image, 127, 255, cv2.THRESH_TOZERO_INV)
show_img('TOZERO_INV', mask5)
2.2 二值化參數(中文表格來自於STEAM 教育學習網)
2.3 執行結果
侵蝕膨脹
3.1 影像侵蝕:以Kernel(卷積核)滑動進行卷積運算,使影像中白色區域縮小、黑色區域擴大。
用途:可用於去除影像中的噪點或加粗字跡。
程式碼
import cv2
import numpy as np
# 顯示圖檔
def show_img(name, img):
cv2.imshow(name, img)
cv2.waitKey(0)
image_path = './over_brain.jpg'
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
image = cv2.resize(image, (300, 300))
show_img('origin', image)
kernel = np.ones((3, 3), np.uint8)
erode_image = cv2.erode(image, kernel, iterations=1)
show_img('erode_image', erode_image)
執行結果
3.2 膨脹:以Kernel(卷積核)滑動進行卷積運算,使影像中白色區域擴大、黑色區域縮小。
用途:可用於填補影像中的小孔洞或使字跡變細。
程式碼
import cv2
import numpy as np
# 顯示圖檔
def show_img(name, img):
cv2.imshow(name, img)
cv2.waitKey(0)
image_path = './over_brain.jpg'
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
image = cv2.resize(image, (300, 300))
show_img('origin', image)
kernel = np.ones((3, 3), np.uint8)
dilate_image = cv2.dilate(image, kernel, iterations=1)
show_img('dilate_image', dilate_image)
執行結果
讓我們繼續看下去...