基于OpenCV的Python图像裁剪求助:分割等尺寸图像并去冗余
图像裁剪需求与问题
需要将下方图像分割为两张尺寸相同的图像用于对比,同时去除两张图像之间的冗余区域。

我使用了以下代码进行裁剪,但效果不理想:
import cv2 import numpy as np # Đọc bức ảnh gốc image = cv2.imread('2.jpg') # Lấy chiều cao và chiều rộng của ảnh height, width = image.shape[:2] # Tính vị trí cắt giữa hai ảnh middle = width // 2 # Cắt và lấy hai phần bức ảnh image1 = image[:, :middle] image2 = image[:, middle:] # Tìm contours trong ảnh 1 gray1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY) _, thresh1 = cv2.threshold(gray1, 1, 255, cv2.THRESH_BINARY) contours1, _ = cv2.findContours(thresh1, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) x1, _, w1, _ = cv2.boundingRect(contours1[0]) # Tìm contours trong ảnh 2 gray2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY) _, thresh2 = cv2.threshold(gray2, 1, 255, cv2.THRESH_BINARY) contours2, _ = cv2.findContours(thresh2, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) x2, _, w2, _ = cv2.boundingRect(contours2[0]) # Cắt bỏ vùng đen giữa hai ảnh image1 = image1[:, x1:(x1+w1)] image2 = image2[:, x2:(x2+w2)] # Hiển thị hai ảnh đã cắt cv2.imshow('Image 1', image1) cv2.imshow('Image 2', image2) cv2.waitKey(0) cv2.destroyAllWindows()
改进后的裁剪代码
原代码直接从中间分割后单独处理左右区域,无法保证最终尺寸一致,且阈值设置过低易受噪声干扰。以下是调整后的方案:
import cv2 import numpy as np # 读取原始图像 image = cv2.imread('2.jpg') if image is None: print("无法读取图像,请检查文件路径") exit() # 转为灰度图并二值化,过滤背景噪声 gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) _, thresh = cv2.threshold(gray, 10, 255, cv2.THRESH_BINARY) # 查找外轮廓并按x坐标排序,区分左右有效区域 contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) contours = sorted(contours, key=lambda c: cv2.boundingRect(c)[0]) # 获取左右区域的边界框 x1, y1, w1, h1 = cv2.boundingRect(contours[0]) x2, y2, w2, h2 = cv2.boundingRect(contours[1]) # 统一目标尺寸:取两个区域的最小宽高,确保两张图尺寸一致 target_width = min(w1, w2) target_height = min(h1, h2) # 裁剪到目标尺寸 image_left = image[y1:y1+target_height, x1:x1+target_width] image_right = image[y2:y2+target_height, x2:x2+target_width] # 保存结果或显示 cv2.imwrite('cropped_left.jpg', image_left) cv2.imwrite('cropped_right.jpg', image_right) cv2.imshow('Cropped Left', image_left) cv2.imshow('Cropped Right', image_right) cv2.waitKey(0) cv2.destroyAllWindows()
代码说明
- 对整图做二值化和轮廓检测,直接定位左右两个有效区域,避免中间分割带来的冗余
- 按轮廓x坐标排序,确保左侧区域优先被处理
- 取两个区域的最小宽高作为统一尺寸,保证最终两张图完全适配对比需求
- 增加图像读取失败的判断,提升代码鲁棒性
内容的提问来源于stack exchange,提问作者Peter Basaw
相关产品推荐
相关产品推荐

