Python圖像處理必備技巧分享
下面為你介紹Python圖像處理時需要掌握的15個基本技能:
1. 圖像讀取與保存
借助OpenCV、Pillow(PIL)或者Matplotlib庫,能夠讀取和保存各類格式的圖像文件。
import cv2
from PIL import Image
import matplotlib.pyplot as plt
# OpenCV讀取與保存
img_cv = cv2.imread('image.jpg') # BGR格式
cv2.imwrite('output.jpg', img_cv)
# Pillow讀取與保存
img_pil = Image.open('image.jpg')
img_pil.save('output.jpg')
# Matplotlib讀取與顯示
img_plt = plt.imread('image.jpg')
plt.imshow(img_plt)
2. 圖像顏色空間轉(zhuǎn)換
能夠在RGB、BGR、HSV、灰度等不同顏色空間之間進行轉(zhuǎn)換。
# BGR轉(zhuǎn)RGB img_rgb = cv2.cvtColor(img_cv, cv2.COLOR_BGR2RGB) # BGR轉(zhuǎn)灰度 img_gray = cv2.cvtColor(img_cv, cv2.COLOR_BGR2GRAY) # RGB轉(zhuǎn)HSV import numpy as np hsv_img = cv2.cvtColor(img_cv, cv2.COLOR_BGR2HSV)
3. 圖像裁剪與調(diào)整大小
可以對圖像進行裁剪、調(diào)整尺寸、縮放以及旋轉(zhuǎn)等操作。
# 裁剪 cropped = img_cv[100:300, 200:400] # 裁剪[y1:y2, x1:x2] # 調(diào)整大小 resized = cv2.resize(img_cv, (500, 300)) # 指定寬高 resized = cv2.resize(img_cv, None, fx=0.5, fy=0.5) # 按比例縮放 # 旋轉(zhuǎn) rows, cols = img_cv.shape[:2] M = cv2.getRotationMatrix2D((cols/2, rows/2), 90, 1) rotated = cv2.warpAffine(img_cv, M, (cols, rows))
4. 圖像濾波與平滑
可應(yīng)用各種濾波器來減少噪聲或者對圖像進行平滑處理。
# 高斯模糊 blur = cv2.GaussianBlur(img_cv, (5, 5), 0) # 中值濾波(適用于椒鹽噪聲) median = cv2.medianBlur(img_cv, 5) # 雙邊濾波(保留邊緣) bilateral = cv2.bilateralFilter(img_cv, 9, 75, 75)
5. 邊緣檢測
能檢測圖像中的邊緣,常見的有Canny邊緣檢測和Sobel算子。
# Canny邊緣檢測 edges = cv2.Canny(img_gray, 100, 200) # Sobel邊緣檢測 sobelx = cv2.Sobel(img_gray, cv2.CV_64F, 1, 0, ksize=3) sobely = cv2.Sobel(img_gray, cv2.CV_64F, 0, 1, ksize=3) edges = np.sqrt(sobelx**2 + sobely**2)
6. 閾值處理
通過設(shè)定閾值,將圖像轉(zhuǎn)換為二值圖像。
# 簡單閾值
ret, thresh = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
# 自適應(yīng)閾值
thresh = cv2.adaptiveThreshold(img_gray, 255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY, 11, 2)
# Otsu閾值
ret, thresh = cv2.threshold(img_gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
7. 形態(tài)學(xué)操作
包括膨脹、腐蝕、開運算和閉運算等形態(tài)學(xué)操作。
# 定義結(jié)構(gòu)元素 kernel = np.ones((5,5), np.uint8) # 腐蝕 erosion = cv2.erode(img_gray, kernel, iterations=1) # 膨脹 dilation = cv2.dilate(img_gray, kernel, iterations=1) # 開運算(先腐蝕后膨脹) opening = cv2.morphologyEx(img_gray, cv2.MORPH_OPEN, kernel) # 閉運算(先膨脹后腐蝕) closing = cv2.morphologyEx(img_gray, cv2.MORPH_CLOSE, kernel)
8. 直方圖處理
可以計算和顯示圖像的直方圖,還能進行直方圖均衡化以增強對比度。
# 計算直方圖 hist = cv2.calcHist([img_gray], [0], None, [256], [0, 256]) # 直方圖均衡化 equ = cv2.equalizeHist(img_gray) # 自適應(yīng)直方圖均衡化 clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8)) cl1 = clahe.apply(img_gray)
9. 特征檢測與描述
能夠檢測圖像中的關(guān)鍵點并提取特征描述符,如SIFT、SURF、ORB等。
# ORB特征檢測 orb = cv2.ORB_create() keypoints, descriptors = orb.detectAndCompute(img_gray, None) # 繪制關(guān)鍵點 img_kp = cv2.drawKeypoints(img_gray, keypoints, None, color=(0,255,0), flags=0) # SIFT特征檢測(需要安裝opencv-contrib-python) sift = cv2.SIFT_create() keypoints, descriptors = sift.detectAndCompute(img_gray, None)
10. 圖像配準與特征匹配
可以匹配不同圖像間的特征點,進而實現(xiàn)圖像對齊。
# 特征匹配 bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True) matches = bf.match(des1, des2) matches = sorted(matches, key=lambda x: x.distance) # 單應(yīng)性矩陣估計與圖像配準 src_pts = np.float32([ kp1[m.queryIdx].pt for m in matches ]).reshape(-1,1,2) dst_pts = np.float32([ kp2[m.trainIdx].pt for m in matches ]).reshape(-1,1,2) H, _ = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0) aligned = cv2.warpPerspective(img1, H, (img2.shape[1], img2.shape[0]))
11. 輪廓檢測與分析
能夠檢測圖像中的輪廓,并計算輪廓的面積、周長等參數(shù)。
# 輪廓檢測 contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # 繪制輪廓 img_contours = img_cv.copy() cv2.drawContours(img_contours, contours, -1, (0,255,0), 3) # 輪廓分析 cnt = contours[0] area = cv2.contourArea(cnt) perimeter = cv2.arcLength(cnt, True)
12. 圖像分割
可將圖像分割為不同的區(qū)域,如使用GrabCut或 watershed算法。
# GrabCut分割
mask = np.zeros(img_cv.shape[:2], np.uint8)
bgdModel = np.zeros((1,65), np.float64)
fgdModel = np.zeros((1,65), np.float64)
rect = (50,50,450,290) # ROI區(qū)域
cv2.grabCut(img_cv, mask, rect, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_RECT)
mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')
img_seg = img_cv*mask2[:,:,np.newaxis]
# Watershed分割
ret, thresh = cv2.threshold(img_gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
kernel = np.ones((3,3), np.uint8)
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)
sure_bg = cv2.dilate(opening, kernel, iterations=3)
dist_transform = cv2.distanceTransform(opening, cv2.DIST_L2, 5)
ret, sure_fg = cv2.threshold(dist_transform, 0.7*dist_transform.max(), 255, 0)
unknown = cv2.subtract(sure_bg, sure_fg)
13. 模板匹配
可以在圖像中查找特定的模板。
template = cv2.imread('template.jpg', 0)
h, w = template.shape[:2]
# 模板匹配
res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
# 獲取匹配位置并繪制矩形
top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
cv2.rectangle(img_cv, top_left, bottom_right, 255, 2)
14. 透 視變換與仿射變換
能夠?qū)D像進行透 視校正和仿射變換。
# 透 視變換 pts1 = np.float32([[56,65],[368,52],[28,387],[389,390]]) pts2 = np.float32([[0,0],[300,0],[0,300],[300,300]]) M = cv2.getPerspectiveTransform(pts1, pts2) dst = cv2.warpPerspective(img_cv, M, (300, 300)) # 仿射變換 pts1 = np.float32([[50,50],[200,50],[50,200]]) pts2 = np.float32([[10,100],[200,50],[100,250]]) M = cv2.getAffineTransform(pts1, pts2) dst = cv2.warpAffine(img_cv, M, (cols, rows))
15. 傅里葉變換
可用于頻域分析和濾波。
# 傅里葉變換 f = np.fft.fft2(img_gray) fshift = np.fft.fftshift(f) magnitude_spectrum = 20*np.log(np.abs(fshift)) # 逆傅里葉變換 rows, cols = img_gray.shape crow, ccol = rows//2, cols//2 fshift[crow-30:crow+30, ccol-30:ccol+30] = 0 # 低通濾波 f_ishift = np.fft.ifftshift(fshift) img_back = np.fft.ifft2(f_ishift) img_back = np.abs(img_back)
以上這些技能都是Python圖像處理的基礎(chǔ),你可以根據(jù)具體需求進行拓展和組合使用。
到此這篇關(guān)于Python圖像處理必備技巧分享的文章就介紹到這了,更多相關(guān)Python圖像處理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python如何獲取tensor()數(shù)據(jù)類型中的值
這篇文章主要介紹了python如何獲取tensor()數(shù)據(jù)類型中的值,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07
淺談pytorch grad_fn以及權(quán)重梯度不更新的問題
今天小編就為大家分享一篇淺談pytorch grad_fn以及權(quán)重梯度不更新的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08
Python實現(xiàn)Web應(yīng)用國際化i18n的示例詳解
這篇文章主要為大家詳細介紹了如何基于Python的gettext模塊,實現(xiàn)一個靈活、可擴展的多語言支持系統(tǒng),文中的示例代碼講解詳細,有需要的可以參考下2025-02-02
使用FastCGI部署Python的Django應(yīng)用的教程
這篇文章主要介紹了使用FastCGI部署Python的Django應(yīng)用的教程,FastCGI也是被最廣泛的應(yīng)用于Python框架和服務(wù)器連接的模塊,需要的朋友可以參考下2015-07-07
django-rest-swagger的優(yōu)化使用方法
今天小編就為大家分享一篇django-rest-swagger的優(yōu)化使用方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08

