python 根据坐标将图片进行裁图
功能”
1.给一个图片,并给出图片中所有目标的坐标
2.将图中给出的坐标用框给标注出来
3.经典需求,通常称为“阅读顺序排序”或“Z字排序”。你需要先按行(从上到下)排序,在同一行内再按列(从左到右)排序。将排完序的多个框进行编号
4.对目标框进行裁图
import cv2
import numpy as np
import osdef test():path = "D:\LAELAOI\Test"pointtxt = os.path.join(path, "label_position.txt")with open(pointtxt, 'r')as f:content = f.readlines()print(content)boxes = []for i in content:parts = i.split(',')file = parts[0]x1, x2, y1, y2 = parts[2],parts[3],parts[4],parts[5].strip()print(file, x1, y1, x2, y2)boxes.append([x1, y1, x2, y2])# 进行排序# key=lambda box: (int(box[1]), int(box[0])) 表示:# 1. 先按 box 的第 1 个元素(y1)进行升序排序(从上到下)# 2. 如果 y1 相同,再按第 0 个元素(x1)进行升序排序(从左到右)# 3. int() 是为了将字符串转为数字,确保正确排序sorted_boxes = sorted(boxes, key=lambda box: (int(box[1]), int(box[0])))img = cv2.imread(r"D:\LAELAOI\Test\L_main_CAM_basler.jpg")# img = cv2.resize(img, (1500, 1000))copy_img = img.copy()# 遍历排序后的列表,进行编号(从1开始)# for index, box in enumerate(sorted_boxes, 1):# x1, x2, y1, y2 = int(box[0]), int(box[1]), int(box[2]), int(box[3])# cv2.rectangle(copy_img,(int(box[0]),int(box[1])), (int(box[2]),int(box[3])), (0,0, 255), 2)# print(f"编号: {index}, 坐标: {box}")# --- 主要修改和新增的逻辑在这里 ---for index, box in enumerate(sorted_boxes, 1):# 1. 将字符串坐标转换为整数x1, y1, x2, y2 = map(int, box)# 2. 【关键修复】确保坐标顺序正确,防止计算负数半径# 重新计算左上角和右下角坐标,确保 x1 <= x2, y1 <= y2top_left_x = min(x1, x2)top_left_y = min(y1, y2)bottom_right_x = max(x1, x2)bottom_right_y = max(y1, y2)# 3. 绘制矩形框(使用修正后的坐标)cv2.rectangle(copy_img, (top_left_x, top_left_y), (bottom_right_x, bottom_right_y), (0, 0, 255), 2)# --- 新增代码开始 ---# 4. 计算矩形中心点center_x = (top_left_x + bottom_right_x) // 2center_y = (top_left_y + bottom_right_y) // 2# 7. 在圆圈中心写入编号font = cv2.FONT_HERSHEY_SIMPLEXtext = str(index)# 计算文字大小,以便居中(text_width, text_height), baseline = cv2.getTextSize(text, font, 1, 2)# 计算文字的坐标,使其在圆圈内居中text_x = center_x - text_width // 2text_y = center_y + text_height // 2# 绘制文字# 参数:图像, 文字, 坐标, 字体, 大小, 颜色(白色), 粗细cv2.putText(copy_img, text, (text_x, text_y), font, 10, (0, 0, 255), 3)# --- 新增代码结束 ---print(f"编号: {index}, 原始坐标: {box}, 修正后坐标: {[top_left_x, top_left_y, bottom_right_x, bottom_right_y]}")cropped_img = img[y1:y2, x1:x2]savefile = r"D:\LAELAOI\Test\{}.jpg".format(index)print(savefile)cv2.imwrite(savefile, cropped_img)cv2.imwrite(r"D:\LAELAOI\Test\1111L_main_CAM_basler.jpg", copy_img)cv2.imshow('rr', copy_img)cv2.waitKey(0)cv2.destroyAllWindows()
if __name__ == '__main__':test()
效果图

