睢宁王健林 发表于 2023-9-24 23:37:20

Python 结合opencv实现图片截取和拼接

实践环境

python 3.6.2
scikit-build-0.16.7
win10
opencv_python-4.5.4.60-cp36-cp36m-win_amd64.whl
下载地址:
https://pypi.org/project/opencv-python/4.5.4.60/#files
https://files.pythonhosted.org/packages/57/6c/7f4f56b2555d5c25dd4f41fc72a16dc6402cb2b4f967da11d8d26c669b55/opencv_python-4.5.4.60-cp36-cp36m-win_amd64.whl
注意:下载时不用下abi版的,比如 opencv_python-4.6.0.66-cp36-abi3-win_amd64.whl 不能用,
因为数据类型为 np.uint8,也就是0~255,
依赖包安装

pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple scikit-build # 解决   ModuleNotFoundError: No module named 'skbuild'问题
pip install opencv_python-4.5.4.60-cp36-cp36m-win_amd64.whl代码实践

示例图片


代码

import os
import numpy as np
import cv2
from datetime import datetime
from PIL import Image

def capture_image(image_file_path, left, upper, width, height, target_file_name=None):
    '''截取图片'''

    right = left + width
    lower = upper + height
    if os.path.exists(image_file_path):
      image = Image.open(image_file_path)
      # width, height = image.size
      # print('图片宽度', width, '图片高度', height)

      head, ext = os.path.splitext(image_file_path)
      if not target_file_name:
            target_file_name = 'pic_captured%s%s' % (datetime.now().strftime('%Y%m%d%H%M%S%f'), ext)

      target_file_path = '%s%s' % (head, target_file_name)
      image.crop((left, upper, right, lower)).save(target_file_path)
      return target_file_path
    else:
      error_msg = '图片文件路径不存在:%s' % image_file_path
      print(error_msg)
      raise Exception(error_msg)


def append_picture(image1_path, image2_path):
    '''拼接图片'''

    image1 = cv2.imread(image1_path, -1)
    shape = image1.shape
    height1, width1, channel1 = shape
    # print(shape)   # 输出:(315, 510, 4)
    # print(image1)    # 输出一3维数组
    # print(len(image1), len(image1))# 输出:315 510

    image2 = cv2.imread(image2_path, -1)
    height2, width2, channel2 =image2.shape

    total_height = max(height1, height2)
    total_width = width1 + width2

    dst = np.zeros((total_height, total_width, channel1), np.uint8)
    dst = image1

    dst = image2
    cv2.imwrite("merge.png", dst)

if __name__ == '__main__':
    # 截取图片
    image_path1 = capture_image('example.png', 10, 30, 510, 315)
    image_path2 = capture_image('example.png', 520, 30, 518, 315)

    append_picture(image_path1, image_path2)运行结果

截取的图片


合并的图片

代码补充说明


来源:https://www.cnblogs.com/shouke/p/17727001.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: Python 结合opencv实现图片截取和拼接