import os
import cv2
import numpy as np
import json
def compute_iou(rect1, rect2):
# Compute IoU between two rectangles
x1, y1, w1, h1 = rect1
x2, y2, w2, h2 = rect2
# Compute intersection
xi1 = max(x1, x2)
yi1 = max(y1, y2)
xi2 = min(x1 + w1, x2 + w2)
yi2 = min(y1 + h1, y2 + h2)
inter_width = max(0, xi2 - xi1)
inter_height = max(0, yi2 - yi1)
inter_area = inter_width * inter_height
# Compute union
area1 = w1 * h1
area2 = w2 * h2
union_area = area1 + area2 - inter_area
if union_area == 0:
return 0
else:
return inter_area / union_area
def merge_rectangles(rectangles):
merged = True
while merged:
merged = False
new_rectangles = []
skip_indices = set()
i = 0
while i < len(rectangles):
if i in skip_indices:
i += 1
continue
rect1 = rectangles[i]
x1, y1, w1, h1 = rect1
merged_this_round = False
for j in range(len(rectangles)):
if j == i or j in skip_indices:
continue
rect2 = rectangles[j]
x2, y2, w2, h2 = rect2
# Vertical merging
if abs(x1 - x2) <= 5 and abs(w1 - w2) <= 5 and \
(abs((y1 + h1) - y2) <=5 or abs((y2 + h2) - y1) <=5):
x_new = min(x1, x2)
y_new = min(y1, y2)
w_new = max(x1 + w1, x2 + w2) - x_new
h_new = max(y1 + h1, y2 + h2) - y_new
new_rectangles.append((x_new, y_new, w_new, h_new))
skip_indices.add(i)
skip_indices.add(j)
merged = True
merged_this_round = True
break
# Horizontal merging
elif abs(y1 - y2) <=5 and abs(h1 - h2) <=5 and \
(abs((x1 + w1) - x2) <=5 or abs((x2 + w2) - x1) <=5):
x_new = min(x1, x2)
y_new = min(y1, y2)
w_new = max(x1 + w1, x2 + w2) - x_new
h_new = max(y1 + h1, y2 + h2) - y_new
new_rectangles.append((x_new, y_new, w_new, h_new))
skip_indices.add(i)
skip_indices.add(j)
merged = True
merged_this_round = True
break
if not merged_this_round and i not in skip_indices:
new_rectangles.append(rect1)
skip_indices.add(i)
i +=1
rectangles = new_rectangles
return rectangles
def process_image(image_path):
# Read image
image = cv2.imread(image_path)
if image is None:
print(f"无法读取图片:{image_path}")
return
image_height, image_width = image.shape[:2]
# Convert to HSV and create blue mask
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
lower_blue = np.array([100, 150, 50])
upper_blue = np.array([140, 255, 255])
mask = cv2.inRange(hsv, lower_blue, upper_blue)
# Find contours
contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
rectangles = []
for contour in contours:
x, y, w, h = cv2.boundingRect(contour)
if w > 20 and h > 20:
rectangles.append((x, y, w, h))
# Merge rectangles
rectangles = merge_rectangles(rectangles)
# Prepare for step (5)
rectangle_areas = [w*h for x,y,w,h in rectangles]
num_rects = len(rectangles)
image_area = image_width * image_height
# Apply filtering per requirements
if num_rects < 4:
# Step 1
rectangles_to_remove = set()
for i in range(len(rectangles)):
for j in range(i +1, len(rectangles)):
if i in rectangles_to_remove or j in rectangles_to_remove:
continue
rect_i = rectangles[i]
rect_j = rectangles[j]
iou = compute_iou(rect_i, rect_j)
if iou > 0.9:
area_i = rectangle_areas[i]
area_j = rectangle_areas[j]
if area_i >= area_j:
rectangles_to_remove.add(j)
else:
rectangles_to_remove.add(i)
rectangles = [rect for idx, rect in enumerate(rectangles) if idx not in rectangles_to_remove]
elif num_rects == 4:
# Step 2
areas_and_indices = [(area, idx) for idx, area in enumerate(rectangle_areas)]
areas_and_indices.sort()
idx_to_remove = [areas_and_indices[0][1], areas_and_indices[-1][1]]
rectangles = [rect for idx, rect in enumerate(rectangles) if idx not in idx_to_remove]
elif num_rects >4:
# Step 3a
rectangles_filtered = []
rectangle_areas_filtered = []
for rect in rectangles:
x, y, w, h = rect
if w / h > 5 or h / w > 5:
continue
rectangles_filtered.append(rect)
rectangle_areas_filtered.append(w*h)
rectangles = rectangles_filtered
rectangle_areas = rectangle_areas_filtered
num_rects = len(rectangles)
# Step 3b
large_rectangles_indices = [idx for idx, area in enumerate(rectangle_areas) if area >= 0.9 * image_area]
if large_rectangles_indices:
rectangles = [rect for idx, rect in enumerate(rectangles) if idx not in large_rectangles_indices]
rectangle_areas = [w*h for x,y,w,h in rectangles]
areas_and_indices = [(area, idx) for idx, area in enumerate(rectangle_areas)]
areas_and_indices.sort(reverse=True)
top_three_indices = [idx for area, idx in areas_and_indices[:3]]
rectangles = [rect for idx, rect in enumerate(rectangles) if idx in top_three_indices]
else:
areas_and_indices = [(area, idx) for idx, area in enumerate(rectangle_areas)]
areas_and_indices.sort(reverse=True)
idx_to_remove = areas_and_indices[0][1]
top_three_indices = [idx for area, idx in areas_and_indices[1:4]]
rectangles = [rect for idx, rect in enumerate(rectangles) if idx in top_three_indices]
# Step 4
num_rects = len(rectangles)
rectangle_areas = [w*h for x,y,w,h in rectangles]
rectangles_to_remove = set()
for i in range(num_rects):
rect_i = rectangles[i]
x1, y1, w1, h1 = rect_i
count_contained = 0
index_contained = []
for j in range(num_rects):
if i == j:
continue
rect_j = rectangles[j]
x2, y2, w2, h2 = rect_j
if x2 >= x1 and y2 >= y1 and (x2 + w2) <= (x1 + w1) and (y2 + h2) <= (y1 + h1):
count_contained +=1
index_contained.append(j)
if count_contained ==2:
rectangles_to_remove.add(i)
elif count_contained ==1:
area_i = rectangle_areas[i]
area_j = rectangle_areas[index_contained[0]]
if area_i > area_j:
rectangles_to_remove.add(index_contained[0])
rectangles = [rect for idx, rect in enumerate(rectangles) if idx not in rectangles_to_remove]
# Output coordinates and image dimensions
print(f"图片名:{os.path.basename(image_path)};图片大小尺寸:{image_width}*{image_height};有{len(rectangles)}个蓝色矩形框的坐标:")
for rect in rectangles:
x, y, w, h = rect
points = [
[x, y],
[x + w, y],
[x + w, y + h],
[x, y + h]
]
print(f"{points}")
# Generate JSON file
shapes = []
for rect in rectangles:
x, y, w, h = rect
points = [
[x, y], # 左上
[x + w, y], # 右上
[x + w, y + h], # 右下
[x, y + h] # 左下
]
shape = {
"label": "烟",
"points": points,
"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
}
# Write JSON file
base_name = os.path.basename(image_path)
name_without_ext = os.path.splitext(base_name)[0]
json_filename = os.path.join(os.path.dirname(image_path), name_without_ext + '.json')
with open(json_filename, 'w', encoding='utf-8') as json_file:
json.dump(json_data, json_file, ensure_ascii=False, indent=4)
def process_images_in_directory(input_dir):
for filename in os.listdir(input_dir):
if filename.lower().endswith('.jpg') or filename.lower().endswith('.jpeg'):
image_path = os.path.join(input_dir, filename)
process_image(image_path)
# 输入图片所在的文件夹路径
input_dir = "C:/Users/xuesa/Desktop/picture/"
# 处理文件夹中的所有图片
process_images_in_directory(input_dir)