下面为你介绍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. 图像颜色空间转换
能够在rgb、bgr、hsv、灰度等不同颜色空间之间进行转换。
# bgr转rgb img_rgb = cv2.cvtcolor(img_cv, cv2.color_bgr2rgb) # bgr转灰度 img_gray = cv2.cvtcolor(img_cv, cv2.color_bgr2gray) # rgb转hsv import numpy as np hsv_img = cv2.cvtcolor(img_cv, cv2.color_bgr2hsv)
3. 图像裁剪与调整大小
可以对图像进行裁剪、调整尺寸、缩放以及旋转等操作。
# 裁剪 cropped = img_cv[100:300, 200:400] # 裁剪[y1:y2, x1:x2] # 调整大小 resized = cv2.resize(img_cv, (500, 300)) # 指定宽高 resized = cv2.resize(img_cv, none, fx=0.5, fy=0.5) # 按比例缩放 # 旋转 rows, cols = img_cv.shape[:2] m = cv2.getrotationmatrix2d((cols/2, rows/2), 90, 1) rotated = cv2.warpaffine(img_cv, m, (cols, rows))
4. 图像滤波与平滑
可应用各种滤波器来减少噪声或者对图像进行平滑处理。
# 高斯模糊 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. 阈值处理
通过设定阈值,将图像转换为二值图像。
# 简单阈值 ret, thresh = cv2.threshold(img_gray, 127, 255, cv2.thresh_binary) # 自适应阈值 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. 形态学操作
包括膨胀、腐蚀、开运算和闭运算等形态学操作。
# 定义结构元素 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) # 自适应直方图均衡化 clahe = cv2.createclahe(cliplimit=2.0, tilegridsize=(8,8)) cl1 = clahe.apply(img_gray)
9. 特征检测与描述
能够检测图像中的关键点并提取特征描述符,如sift、surf、orb等。
# orb特征检测 orb = cv2.orb_create() keypoints, descriptors = orb.detectandcompute(img_gray, none) # 绘制关键点 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. 图像配准与特征匹配
可以匹配不同图像间的特征点,进而实现图像对齐。
# 特征匹配 bf = cv2.bfmatcher(cv2.norm_hamming, crosscheck=true) matches = bf.match(des1, des2) matches = sorted(matches, key=lambda x: x.distance) # 单应性矩阵估计与图像配准 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. 轮廓检测与分析
能够检测图像中的轮廓,并计算轮廓的面积、周长等参数。
# 轮廓检测 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. 图像分割
可将图像分割为不同的区域,如使用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区域 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. 透 视变换与仿射变换
能够对图像进行透 视校正和仿射变换。
# 透 视变换 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图像处理的基础,你可以根据具体需求进行拓展和组合使用。
到此这篇关于python图像处理必备技巧分享的文章就介绍到这了,更多相关python图像处理内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论