翼度科技»论坛 编程开发 python 查看内容

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

2

主题

2

帖子

6

积分

新手上路

Rank: 1

积分
6
实践环境

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,
依赖包安装
  1. pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple scikit-build # 解决     ModuleNotFoundError: No module named 'skbuild'问题
  2. pip install opencv_python-4.5.4.60-cp36-cp36m-win_amd64.whl
复制代码
代码实践

示例图片


代码
  1. import os
  2. import numpy as np
  3. import cv2
  4. from datetime import datetime
  5. from PIL import Image
  6. def capture_image(image_file_path, left, upper, width, height, target_file_name=None):
  7.     '''截取图片'''
  8.     right = left + width
  9.     lower = upper + height
  10.     if os.path.exists(image_file_path):
  11.         image = Image.open(image_file_path)
  12.         # width, height = image.size
  13.         # print('图片宽度', width, '图片高度', height)
  14.         head, ext = os.path.splitext(image_file_path)
  15.         if not target_file_name:
  16.             target_file_name = 'pic_captured%s%s' % (datetime.now().strftime('%Y%m%d%H%M%S%f'), ext)
  17.         target_file_path = '%s%s' % (head, target_file_name)
  18.         image.crop((left, upper, right, lower)).save(target_file_path)
  19.         return target_file_path
  20.     else:
  21.         error_msg = '图片文件路径不存在:%s' % image_file_path
  22.         print(error_msg)
  23.         raise Exception(error_msg)
  24. def append_picture(image1_path, image2_path):
  25.     '''拼接图片'''
  26.     image1 = cv2.imread(image1_path, -1)
  27.     shape = image1.shape
  28.     height1, width1, channel1 = shape
  29.     # print(shape)     # 输出:(315, 510, 4)
  30.     # print(image1)    # 输出一3维数组
  31.     # print(len(image1), len(image1[0]))  # 输出:315 510
  32.     image2 = cv2.imread(image2_path, -1)
  33.     height2, width2, channel2 =  image2.shape
  34.     total_height = max(height1, height2)
  35.     total_width = width1 + width2
  36.     dst = np.zeros((total_height, total_width, channel1), np.uint8)
  37.     dst[0:height1, 0:width1] = image1
  38.     dst[0:height2, width1:total_width] = image2
  39.     cv2.imwrite("merge.png", dst)
  40. if __name__ == '__main__':
  41.     # 截取图片
  42.     image_path1 = capture_image('example.png', 10, 30, 510, 315)
  43.     image_path2 = capture_image('example.png', 520, 30, 518, 315)
  44.     append_picture(image_path1, image_path2)
复制代码
运行结果

截取的图片


合并的图片

代码补充说明


来源:https://www.cnblogs.com/shouke/p/17727001.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具