python
import cv2
import numpy as np
import os
import json
def get_rectangle_corners(x, y, w, h):
# 返回矩形的四个角点,按照左上,右上,右下,左下的顺序
top_left = [x, y]
top_right = [x + w, y]
bottom_right = [x + w, y + h]
bottom_left = [x, y + h]
return [top_left, top_right, bottom_right, bottom_left]
def merge_rectangles(rects, merge_type):
# 根据合并类型(vertical 或 horizontal)合并矩形框
merged = True
while merged:
merged = False
new_rects = []
skip_indices = set()
for i in range(len(rects)):
if i in skip_indices:
continue
x, y, w, h = rects[i]
merged_this_round = False
for j in range(i+1, len(rects)):
if j in skip_indices:
continue
x1, y1, w1, h1 = rects[j]
if merge_type == 'vertical':
# 检查垂直方向合并条件(步骤3)
if abs(x - x1) <= 5 and abs(w - w1) <= 5 and (abs((y + h1) - y1) <= 5 or abs((y1 + h1) - y) <= 5):
# 合并矩形框
x2 = min(x, x1)
y2 = min(y, y1)
x2_max = max(x + w, x1 + w1)
y2_max = max(y + h, y1 + h1)
w2 = x2_max - x2
h2 = y2_max - y2
new_rects.append((x2, y2, w2, h2))
skip_indices.update([i, j])
merged_this_round = True
merged = True
break
elif merge_type == 'horizontal':
# 检查水平方向合并条件(步骤4)
if abs(y - y1) <= 5 and abs(h - h1) <= 5 and (abs((x + w) - x1) <= 5 or abs((x1 + w1) - x) <= 5):
# 合并矩形框
x2 = min(x, x1)
y2 = min(y, y1)
x2_max = max(x + w, x1 + w1)
y2_max = max(y + h, y1 + h1)
w2 = x2_max - x2
h2 = y2_max - y2
new_rects.append((x2, y2, w2, h2))
skip_indices.update([i, j])
merged_this_round = True
merged = True
break
if not merged_this_round and i not in skip_indices:
new_rects.append((x, y, w, h))
rects = new_rects
return rects
def filter_rectangles(rects, image_area):
# 过滤矩形框(步骤5)
rects_area = [(rect, rect[2]*rect[3]) for rect in rects]
rects_area.sort(key=lambda x: x[1], reverse=True) # 按面积从大到小排序
num_rects = len(rects_area)
filtered_rects = []
if num_rects < 4:
# 保留所有矩形框
filtered_rects = [rect for rect, area in rects_area]
elif num_rects == 4:
# 去掉最大和最小面积的矩形框
filtered_rects = [rect for rect, area in rects_area[1:-1]]
else:
# 删除宽高比大于5的矩形框
rects_area = [rect_area for rect_area in rects_area if not ((rect_area[0][2]/rect_area[0][3]>5) or (rect_area[0][3]/rect_area[0][2]>5))]
# 删除面积占比大于等于90%的矩形框
rects_area = [rect_area for rect_area in rects_area if rect_area[1] < 0.9 * image_area]
if len(rects_area) > 3:
# 保留面积最大的3个矩形框
filtered_rects = [rect_area[0] for rect_area in rects_area[:3]]
else:
# 去除最大的矩形框
if rects_area:
rects_area = rects_area[1:]
# 保留面积次大的3个矩形框
filtered_rects = [rect_area[0] for rect_area in rects_area[:3]]
return filtered_rects
def process_image(image_path, output_directory):
# 读取图片
image = cv2.imread(image_path)
if image is None:
print(f"无法读取图片:{image_path}")
return
image_height, image_width = image.shape[:2]
image_area = image_width * image_height
# 转换为 HSV 色彩空间
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# 定义蓝色的 HSV 范围
lower_blue = np.array([100, 150, 50]) # 蓝色下限
upper_blue = np.array([140, 255, 255]) # 蓝色上限
# 创建掩膜提取蓝色部分
mask = cv2.inRange(hsv, lower_blue, upper_blue)
# 查找轮廓
contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 遍历轮廓,筛选大于 20x20 像素的矩形框
rectangles = []
for contour in contours:
x, y, w, h = cv2.boundingRect(contour)
if w > 20 and h > 20:
rectangles.append((x, y, w, h))
# 输出矩形框的坐标和图片尺寸
for rect in rectangles:
x, y, w, h = rect
corners = get_rectangle_corners(x, y, w, h)
print(f"找到蓝色方框,坐标为:{corners}")
print(f"图片尺寸:宽度={image_width},高度={image_height}")
# 第(3)步处理:垂直方向合并矩形框
merged_rects_v = merge_rectangles(rectangles, 'vertical')
# 保存处理结果图片 result_1
image_result_1 = image.copy()
for rect in merged_rects_v:
x, y, w, h = rect
cv2.rectangle(image_result_1, (x, y), (x + w, y + h), (0, 0, 255), 2)
result_1_path = os.path.join(output_directory, os.path.splitext(os.path.basename(image_path))[0] + '_result_1.jpg')
cv2.imwrite(result_1_path, image_result_1)
print(f"垂直合并结果已保存为:{result_1_path}")
# 第(4)步处理:水平方向合并矩形框
merged_rects_h = merge_rectangles(merged_rects_v, 'horizontal')
# 保存处理结果图片 result_2
image_result_2 = image.copy()
for rect in merged_rects_h:
x, y, w, h = rect
cv2.rectangle(image_result_2, (x, y), (x + w, y + h), (0, 0, 255), 2)
result_2_path = os.path.join(output_directory, os.path.splitext(os.path.basename(image_path))[0] + '_result_2.jpg')
cv2.imwrite(result_2_path, image_result_2)
print(f"水平合并结果已保存为:{result_2_path}")
# 第(5)步处理:过滤矩形框
filtered_rects = filter_rectangles(merged_rects_h, image_area)
# 准备写入 json 文件的数据
shapes = []
for rect in filtered_rects:
x, y, w, h = rect
corners = get_rectangle_corners(x, y, w, h)
shape = {
"label": "烟",
"points": corners,
"group_id": None,
"description": "",
"difficult": False,
"shape_type": "rectangle",
"flags": {},
"attributes": {}
}
shapes.append(shape)
json_data = {
"version": "2.3.5",
"flags": {},
"shapes": shapes,
"imagePath": os.path.basename(image_path),
"imageData": None,
"imageHeight": image_height,
"imageWidth": image_width
}
# 第(7)步:保存 json 文件
json_path = os.path.join(output_directory, os.path.splitext(os.path.basename(image_path))[0] + '.json')
with open(json_path, 'w', encoding='utf-8') as f:
json.dump(json_data, f, ensure_ascii=False, indent=4)
print(f"处理完成,结果已保存为:{json_path}")
def main():
# 输入图片所在的文件夹路径
input_directory = "C:/Users/xuesa/Desktop/picture/"
output_directory = input_directory # 结果保存在原始图片的相同目录
# 获取文件夹中所有的 .jpg 文件
image_files = [f for f in os.listdir(input_directory) if f.lower().endswith('.jpg')]
# 遍历并处理每一张图片
for image_file in image_files:
image_path = os.path.join(input_directory, image_file)
process_image(image_path, output_directory)
if __name__ == "__main__":
main()