opencv长方形补全变成正方形
时间: 2024-01-29 15:10:34 浏览: 166
以下是使用OpenCV将长方形图像补全为正方形的方法:
```python
import cv2
import numpy as np
def resize_image(image):
# 获取图像的宽度和高度
height, width = image.shape[:2]
# 计算图像的长边和短边
if height > width:
long_side = height
short_side = width
else:
long_side = width
short_side = height
# 计算缩放比例
scale = long_side / short_side
# 计算补全后的图像尺寸
if height > width:
new_height = int(scale * short_side)
new_width = long_side
else:
new_height = long_side
new_width = int(scale * short_side)
# 创建一个新的正方形图像
square_image = np.zeros((long_side, long_side, 3), dtype=np.uint8)
# 计算补全后的图像的起始位置
start_x = (long_side - new_width) // 2
start_y = (long_side - new_height) // 2
# 将原始图像缩放并复制到正方形图像中
resized_image = cv2.resize(image, (new_width, new_height))
square_image[start_y:start_y+new_height, start_x:start_x+new_width] = resized_image
return square_image
# 读取图像
image = cv2.imread('input.jpg')
# 调用函数将图像补全为正方形
square_image = resize_image(image)
# 显示结果图像
cv2.imshow('Square Image', square_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文