Python图像处理必备技巧分享

Written by

in

文章目录
  • 借助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)
  • 能够在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)
  • 可以对图像进行裁剪、调整尺寸、缩放以及旋转等操作。 # 裁剪 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))
  • 可应用各种滤波器来减少噪声或者对图像进行平滑处理。 # 高斯模糊 blur = cv2.GaussianBlur(img_cv, (5, 5), 0) # 中值滤波(适用于椒盐噪声) median = cv2.medianBlur(img_cv, 5) # 双边滤波(保留边缘) bilateral = cv2.bilateralFilter(img_cv, 9, 75, 75)
  • 能检测图像中的边缘,常见的有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)
  • 通过设定阈值,将图像转换为二值图像。 # 简单阈值 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)
  • 包括膨胀、腐蚀、开运算和闭运算等形态学操作。 # 定义结构元素 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)
  • 可以计算和显示图像的直方图,还能进行直方图均衡化以增强对比度。 # 计算直方图 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)
  • 能够检测图像中的关键点并提取特征描述符,如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)
  • 可以匹配不同图像间的特征点,进而实现图像对齐。 # 特征匹配 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]))
  • 能够检测图像中的轮廓,并计算轮廓的面积、周长等参数。 # 轮廓检测 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)
  • 可将图像分割为不同的区域,如使用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)
  • 可以在图像中查找特定的模板。 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)
  • 能够对图像进行透 视校正和仿射变换。 # 透 视变换 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))
  • 可用于频域分析和滤波。 # 傅里叶变换 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图像处理内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客! 您可能感兴趣的文章: Python实现GPU加速图像处理的代码详解 Python图像处理之给图片添加圆角效果的完整代码 详解Python图像处理中内存泄漏的问题解决方法 Python使用imageio库处理图像与视频的操作详解 使用Python进行图像批处理的方法示例
  • 目录
    • 1. 图像读取与保存
    • 2. 图像颜色空间转换
    • 3. 图像裁剪与调整大小
    • 4. 图像滤波与平滑
    • 5. 边缘检测
    • 6. 阈值处理
    • 7. 形态学操作
    • 8. 直方图处理
    • 9. 特征检测与描述
    • 10. 图像配准与特征匹配
    • 11. 轮廓检测与分析
    • 12. 图像分割
    • 13. 模板匹配
    • 14. 透 视变换与仿射变换
    • 15. 傅里叶变换

    下面为你介绍Python图像处理时需要掌握的15个基本技能:

    借助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)
    

    能够在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)
    

    可以对图像进行裁剪、调整尺寸、缩放以及旋转等操作。

    # 裁剪
    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))
    

    可应用各种滤波器来减少噪声或者对图像进行平滑处理。

    # 高斯模糊
    blur = cv2.GaussianBlur(img_cv, (5, 5), 0)
    
    # 中值滤波(适用于椒盐噪声)
    median = cv2.medianBlur(img_cv, 5)
    
    # 双边滤波(保留边缘)
    bilateral = cv2.bilateralFilter(img_cv, 9, 75, 75)
    

    能检测图像中的边缘,常见的有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)
    

    通过设定阈值,将图像转换为二值图像。

    # 简单阈值
    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)
    

    包括膨胀、腐蚀、开运算和闭运算等形态学操作。

    # 定义结构元素
    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)
    

    可以计算和显示图像的直方图,还能进行直方图均衡化以增强对比度。

    # 计算直方图
    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)
    

    能够检测图像中的关键点并提取特征描述符,如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)
    

    可以匹配不同图像间的特征点,进而实现图像对齐。

    # 特征匹配
    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]))
    

    能够检测图像中的轮廓,并计算轮廓的面积、周长等参数。

    # 轮廓检测
    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)
    

    可将图像分割为不同的区域,如使用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)
    

    可以在图像中查找特定的模板。

    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)
    

    能够对图像进行透 视校正和仿射变换。

    # 透 视变换
    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))
    

    可用于频域分析和滤波。

    # 傅里叶变换
    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图像处理内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!

    您可能感兴趣的文章:

    • Python实现GPU加速图像处理的代码详解
    • Python图像处理之给图片添加圆角效果的完整代码
    • 详解Python图像处理中内存泄漏的问题解决方法
    • Python使用imageio库处理图像与视频的操作详解
    • 使用Python进行图像批处理的方法示例

    站内搜索