Python截取图片区域并保存03

提供一张图片,如何截剪其中的某一部分的区域?

我的思路是分两步:

  1. 找到要裁剪区域的坐标

  2. 根据图片坐标进行剪切,并保存

import cv2
from PIL import Image

def getCoordinate(img):
    rectangle = []
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)        # 灰度图
    ret, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY|cv2.THRESH_OTSU)    # 二值化

    element3 = cv2.getStructuringElement(cv2.MORPH_RECT, (8, 8))    # 设置膨胀和腐蚀操作
    dilation = cv2.dilate(binary, element3, iterations=1)   # 膨胀一次,让轮廓突出
    contours, hierarchy = cv2.findContours(dilation, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_TC89_L1)  # 检测轮廓
    cv2.drawContours(img, contours, -1, (0, 0, 255), 3)  # 参数值为1, 给contours[1]绘制轮廓。 -1: 给所有的contours绘制轮廓
    cv2.imshow("img", img)
    cv2.waitKey()

    for contour in contours:
        x, y, w, h = cv2.boundingRect(contour)
        rectangle.append((x, y, x + w, y + h))
    print(f'rectangle: {rectangle}')
    return rectangle

if __name__ == '__main__':
    imgPath = 'D:\\img.bmp'
    img = cv2.imread(imgPath)
    # 保存
    getCoordinate(img)
import cv2
from PIL import Image

def savePic(rectangle):
    for i in range(len(rectangle)):
        imgPath = "D:\\PythonWork\\Contour\\Photos\\" + str(i+1) + ".PNG"  #notes: 图片的扩展名要一致
        im = Image.open(defaultImgPath)
        im = im.crop(rectangle[i])  # 对图片进行切割 im.crop(top_x, top_y, bottom_x, bottom_y)
        im.save(imgPath)

if __name__ == '__main__':
    defaultImgPath = 'D:\\test.PNG'
    img = cv2.imread(defaultImgPath)
    # 保存图片,getCoordinate()可以查看上一步中的源码
    coordinateValue = getCoordinate(img)
    savePic(coordinateValue)

1. getCoordinate()可以查看一、获取感兴趣图片坐标中的源码

2. 如果指定某一区域坐标,main主函数如下:

if __name__ == '__main__':
    rnt = [(46, 28, 101, 61)]
    savePic(rnt)
  1. cv2.COLOR_BGR2GRAY 将BGR格式转换成灰度图片 灰度图片并不是指常规意义上的黑白图片,只用看是不是无符号八位整型(unit8)

  2. ret,dst = cv2.threshold(src,thresh,maxval,type) #返回的第一个参数为阈值,第二个为结果图像

  3. cv2.threshold(dilation, 0, 255, cv2.THRESH_BINARY) #二值化 将灰度图dilation中灰度值小于0的点置0,灰度值大于255的点置255

  4. cv2.getStructuringElement(shape, ksize)

cv2.getStructuringElement(cv2.MORPH_RECT, (8, 8)) #设置膨胀和腐蚀操作的核函数

cv2.MORPH_RECT: 矩形结构元素,所有元素值都是1 ksize:代表形状元素的大小

  1. cv2.dilate(binary, element3, iterations=1) #膨胀一次,让轮廓突出

  2. cv2.findContours()函数接受的参数为二值图,即黑白的(不是灰度图),所以读取的图像要先转成灰度的,再转成二值图

cv2.findContours(dilation, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_TC89_L1) #查找轮廓

cv2.RETR_EXTERNAL 表示只检测外轮廓

cv2.CHAIN_APPROX_TC89_L1,CV_CHAIN_APPROX_TC89_KCOS 使用teh-Chinl chain 近似算法

cv2.findContours()函数返回两个值,一个是轮廓本身,还有一个是每条轮廓对应的属性。

contours返回值:cv2.findContours()函数首先返回一个list,list中每个元素都是图像中的一个轮廓,用numpy中的ndarray表示。可以通过len(contours)知道返回的轮廓。

  1. cv2.boundingRect(contour):矩形边框(Bounding Rectangle)是说,用一个最小的矩形,把找到的形状包起来。

Original: https://blog.csdn.net/spring_r/article/details/125514686
Author: spring_r
Title: Python截取图片区域并保存03

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/533230/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球