python opencv拼接文件夹下的所有图片
时间: 2023-08-04 18:21:17 浏览: 107
基于opencv的图像拼接(Python,pyqt)
在Python中,可以使用OpenCV库来操作图片,并且可以使用Python内置的os库来操作文件夹。拼接文件夹下的所有图片的方法如下:
1.首先,需要导入OpenCV库和os库。
```
import cv2
import os
```
2.设置文件夹路径和拼接后的图片名称。
```
folder_path = 'folder_path'
output_image_name = 'output_image.jpg'
```
3.获取文件夹下的所有图片路径。
```
image_paths = [os.path.join(folder_path, f) for f in os.listdir(folder_path) if f.endswith('.jpg')]
```
4.读取所有图片并获取图片的大小。
```
images = []
widths = []
heights = []
for image_path in image_paths:
image = cv2.imread(image_path)
images.append(image)
height, width, _ = image.shape
widths.append(width)
heights.append(height)
```
5.计算拼接后的图片大小。
```
max_height = max(heights)
total_width = sum(widths)
```
6.创建一张新的图片,大小为所有图片拼接后的大小。
```
new_image = np.zeros((max_height, total_width, 3), dtype=np.uint8)
```
7.将所有图片拼接到新的图片上。
```
x_offset = 0
for image in images:
new_image[0:image.shape[0], x_offset:x_offset+image.shape[1]] = image
x_offset += image.shape[1]
```
8.保存新的图片。
```
cv2.imwrite(output_image_name, new_image)
```
完整代码如下:
```
import cv2
import os
import numpy as np
folder_path = 'folder_path'
output_image_name = 'output_image.jpg'
image_paths = [os.path.join(folder_path, f) for f in os.listdir(folder_path) if f.endswith('.jpg')]
images = []
widths = []
heights = []
for image_path in image_paths:
image = cv2.imread(image_path)
images.append(image)
height, width, _ = image.shape
widths.append(width)
heights.append(height)
max_height = max(heights)
total_width = sum(widths)
new_image = np.zeros((max_height, total_width, 3), dtype=np.uint8)
x_offset = 0
for image in images:
new_image[0:image.shape[0], x_offset:x_offset+image.shape[1]] = image
x_offset += image.shape[1]
cv2.imwrite(output_image_name, new_image)
```
阅读全文