如何将一张图像的中心对齐到另一张图像的角落
嘿,我来帮你搞定这个图像拼接的需求!用Python的OpenCV就能轻松实现,下面是具体的步骤和代码示例:
提取图像中心区域并放置到另一张图像角落
咱们分步骤来操作,逻辑清晰又好上手:
一、准备工作
首先确保你已经安装了OpenCV和numpy,没装的话先跑这个命令:
pip install opencv-python numpy
二、具体代码实现
import cv2 import numpy as np # 1. 读取两张图像 # 源图像:要提取中心区域的那张 src_img = cv2.imread("source_image.jpg") # 目标图像:要放置中心区域的那张 dst_img = cv2.imread("target_image.jpg") # 2. 设置要提取的中心区域大小(可按需调整,这里以200x200正方形为例) roi_size = 200 src_h, src_w = src_img.shape[:2] # 计算中心区域的左上角坐标 center_x = src_w // 2 - roi_size // 2 center_y = src_h // 2 - roi_size // 2 # 提取中心区域(也就是常说的ROI,感兴趣区域) center_roi = src_img[center_y:center_y+roi_size, center_x:center_x+roi_size] # 3. 将ROI放置到目标图像的角落(这里先演示左上角) # 先检查目标图像尺寸是否足够,避免超出范围报错 dst_h, dst_w = dst_img.shape[:2] if roi_size > dst_h or roi_size > dst_w: print("目标图像尺寸太小啦,放不下指定大小的中心区域!") else: # 左上角位置:从(0,0)开始覆盖 dst_img[0:roi_size, 0:roi_size] = center_roi # 要是想放到其他角落,直接改坐标就行: # 右上角:dst_img[0:roi_size, dst_w-roi_size:dst_w] = center_roi # 左下角:dst_img[dst_h-roi_size:dst_h, 0:roi_size] = center_roi # 右下角:dst_img[dst_h-roi_size:dst_h, dst_w-roi_size:dst_w] = center_roi # 保存结果 cv2.imwrite("result_image.jpg", dst_img) # 可选:显示结果窗口 cv2.imshow("Result", dst_img) cv2.waitKey(0) cv2.destroyAllWindows()
三、关键步骤解释
- 读取图像:用
cv2.imread加载图像时,要确保文件路径正确,不然会读取失败哦。 - 提取中心ROI:通过计算源图像的中心坐标,结合设定的区域大小,用数组切片快速抠出中心区域,这是OpenCV处理图像局部区域的常用技巧。
- 放置到角落:同样用数组切片,把目标图像对应角落的区域替换成提取的中心ROI,提前检查尺寸能避免出现“数组越界”的错误。
如果需要提取非正方形的中心区域,只要把roi_size拆成roi_width和roi_height,调整坐标计算逻辑就可以啦。
内容的提问来源于stack exchange,提问作者ron meroz
相关产品推荐
相关产品推荐

