gtang666 commited on
Commit
d84903a
·
verified ·
1 Parent(s): 16c43c4

Upload InternVL/utils.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. InternVL/utils.py +333 -0
InternVL/utils.py ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from PIL import Image
3
+ import numpy as np
4
+ from copy import deepcopy
5
+ import cv2
6
+ import os
7
+ from tqdm import tqdm
8
+ import shutil
9
+
10
+ def calculate_iou(boxA, boxB,mini=False):
11
+ # 计算交集矩形的坐标
12
+ xA = max(boxA[0], boxB[0])
13
+ yA = max(boxA[1], boxB[1])
14
+ xB = min(boxA[2], boxB[2])
15
+ yB = min(boxA[3], boxB[3])
16
+
17
+ # 计算交集面积
18
+ interArea = max(0, xB - xA) * max(0, yB - yA)
19
+
20
+ # 计算两个边界框的面积
21
+ boxAArea = (boxA[2] - boxA[0]) * (boxA[3] - boxA[1])
22
+ boxBArea = (boxB[2] - boxB[0]) * (boxB[3] - boxB[1])
23
+
24
+ # 计算并集面积
25
+ unionArea = boxAArea + boxBArea - interArea
26
+
27
+ # 计算IoU
28
+ iou = interArea / unionArea
29
+ if mini:
30
+ iou=interArea/min(boxAArea,boxBArea)
31
+ return iou
32
+ def get_all_jpgs(folder_path,suffix='.jpg'):
33
+ """得到文件夹中的所有jpg文件路径"""
34
+ files = os.listdir(folder_path)
35
+ jpg_files = [folder_path+f for f in files if os.path.isfile(os.path.join(folder_path, f)) and f.endswith(suffix)]
36
+ return jpg_files
37
+
38
+ def get_all_jsons(folder_path):
39
+ """得到文件夹中的所有json文件路径"""
40
+ files = os.listdir(folder_path)
41
+ json_files = [folder_path+f for f in files if os.path.isfile(os.path.join(folder_path, f)) and f.endswith('json')]
42
+ return json_files
43
+
44
+ def load_json(pth):
45
+ """加载json文件"""
46
+ with open(pth, 'r', encoding='utf-8') as f:
47
+ data = json.load(f)
48
+ return data
49
+ def save_json(pth,data):
50
+ """保存json文件"""
51
+ with open(pth, 'w', encoding='utf-8') as f:
52
+ json.dump(data, f, ensure_ascii=False, indent=4)
53
+
54
+ def shuffle_lists(list1, list2,seed=42):
55
+ import random
56
+ assert len(list1) == len(list2), "两个列表必须等长"
57
+ random.seed(seed)
58
+ # 创建索引列表
59
+ indices = list(range(len(list1)))
60
+
61
+ # 打乱索引列表
62
+ random.shuffle(indices)
63
+
64
+ # 使用打乱后的索引列表重新排列两个列表
65
+ shuffled_list1 = [list1[i] for i in indices]
66
+ shuffled_list2 = [list2[i] for i in indices]
67
+
68
+ return shuffled_list1, shuffled_list2
69
+
70
+ def most_frequent_rgb(image_array):
71
+ """找一张图片中最frequent的rgb,用于填充mask"""
72
+ # Flatten the image array to a 2D array where each row is an RGB tuple
73
+ pixels = image_array.reshape(-1, image_array.shape[-1])
74
+
75
+ # Use np.unique with return_counts to find unique rows and their counts
76
+ unique_pixels, counts = np.unique(pixels, axis=0, return_counts=True)
77
+
78
+ # Find the index of the most frequent pixel
79
+ most_frequent_index = np.argmax(counts)
80
+
81
+ # Get the most frequent pixel and its count
82
+ most_frequent_pixel = unique_pixels[most_frequent_index]
83
+ frequency = counts[most_frequent_index]
84
+ return most_frequent_pixel, frequency
85
+
86
+ def half_divide(img,data):
87
+ """将图片从中分开,mask被穿过的char,并得到对应的左右json文件"""
88
+ left_data={"shapes":[],"imageHeight":data["imageHeight"],"imageWidth":data["imageWidth"]//2}
89
+ right_data={"shapes":[],"imageHeight":data["imageHeight"],"imageWidth":data["imageWidth"]//2}
90
+
91
+ # 获取原始尺寸
92
+ width, height = img.size
93
+
94
+ # 计算切割点
95
+ split_point = width // 2
96
+ image_array = np.array(img)
97
+ color,_=most_frequent_rgb(image_array)
98
+ modified_image=image_array.copy()
99
+
100
+ to_be_mask=[]
101
+ for item in data['shapes']:
102
+ if len(item['points'])!=2 or len(item['points'][0])!=2 or len(item['points'][1])!=2:
103
+ continue
104
+ [x1,y1],[x2,y2]=item['points']
105
+ if x2<split_point:
106
+ left_data['shapes'].append({"points":[[x1,y1],[x2,y2]]})
107
+ elif x1>split_point:
108
+ right_data['shapes'].append({"points":[[x1-split_point,y1],[x2-split_point,y2]]})
109
+ else:
110
+ to_be_mask.append([x1,y1,x2,y2])
111
+
112
+ for coord in to_be_mask:
113
+ x1, y1, x2, y2 = coord
114
+ modified_image[int(y1):int(y2), int(x1):int(x2)] =color
115
+
116
+ modified_image_pil = Image.fromarray(modified_image)
117
+ left_img = modified_image_pil.crop((0, 0, split_point, height))
118
+ right_img =modified_image_pil.crop((split_point, 0, width, height))
119
+ return [left_img,left_data,right_img,right_data]
120
+
121
+ def refine(jpg_path,json_path,save_dir):
122
+ """对一张图片进行half divide,直到子图都不超过300"""
123
+ data=load_json(json_path)
124
+ n=len(data['shapes'])
125
+ name=jpg_path.split('/')[-1].split('.')[0]
126
+ img = Image.open(jpg_path)
127
+ if n<300:
128
+
129
+ img.save(save_dir+name+f'.jpg')
130
+ save_json(save_dir+name+f'.json',data)
131
+ return None
132
+ else:
133
+ left_img,left_data,right_img,right_data=half_divide(img,data)
134
+ ###储存所有当下的子图和子data
135
+ sub_img=[left_img,right_img]
136
+ sub_data=[left_data,right_data]
137
+ i=0
138
+ while True:
139
+ if i==len(sub_img):
140
+ break
141
+ simg=sub_img[i]
142
+ sdata=sub_data[i]
143
+ if len(sdata['shapes'])>=300:
144
+ sub_img.pop(i)
145
+ sub_data.pop(i)
146
+ li,ld,ri,rd=half_divide(simg,sdata)
147
+ sub_img.append(li)
148
+ sub_img.append(ri)
149
+ sub_data.append(ld)
150
+ sub_data.append(rd)
151
+ i-=1
152
+ i+=1
153
+ j=0
154
+ for pic,d in zip(sub_img,sub_data):
155
+ save_json(save_dir+name+f'_{j}.json',d)
156
+ pic.save(save_dir+name+f'_{j}.jpg')
157
+ j+=1
158
+
159
+ def get_union(b1,b2):
160
+ """求box之间的union,用于合并得列"""
161
+ x1,y1,x2,y2=b1[0][0],b1[0][1],b1[1][0],b1[1][1]
162
+ x3,y3,x4,y4=b2[0][0],b2[0][1],b2[1][0],b2[1][1]
163
+ x=min(x1,x2,x3,x4)
164
+ X=max(x1,x2,x3,x4)
165
+ y=min(y1,y2,y3,y4)
166
+ Y=max(y1,y2,y3,y4)
167
+ return [[x,y],[X,Y]]
168
+ def list_union(boxes):
169
+ """求一个box列表的union,得这列的box"""
170
+ result=boxes[0]
171
+ for item in boxes[1:]:
172
+ result=get_union(result,item)
173
+ return result
174
+ def get_col_jsons(json_files,jpg_files,base,destination_jpgs):
175
+ """从gen_data转换为col_data,注意不是构建数据集,而是对每个json从字得列重新储存"""
176
+ for file_path,jpg_path in tqdm(zip(json_files,jpg_files)):
177
+
178
+ os.makedirs(destination_jpgs, exist_ok=True)
179
+
180
+ # 构建源文件的完整路径
181
+ source_file_path = os.path.join(base, jpg_path)
182
+
183
+ # 构建目标文件的完整路径
184
+ destination_file_path = os.path.join(destination_jpgs, jpg_path)
185
+
186
+ # 复制文件到目标文件夹
187
+ shutil.copy2(source_file_path, destination_file_path)
188
+
189
+ i=file_path.split('.')[0]
190
+ with open(base+file_path, 'r', encoding='utf-8') as file:
191
+ data = json.load(file)
192
+ height=data["imageHeight"]
193
+ width=data["imageWidth"]
194
+ content=data['shapes']
195
+ info=[]
196
+ dic={}
197
+ results=[]
198
+ for item in content:
199
+ col=item['col']
200
+ if col not in dic:
201
+ dic[col]=[item['points']]
202
+ else:
203
+ dic[col].append(item['points'])
204
+ for key,value in dic.items():
205
+ union=list_union(value)
206
+ results.append({'label':key,'points':union})
207
+ data['shapes']=results
208
+ save_json(os.path.join(destination_jpgs,file_path ),data)
209
+ def drawBoxes(results,jpg_path,save_path):
210
+ frame = cv2.imread(jpg_path)
211
+ for points in results:
212
+ x1, y1, x2, y2 = int(points[0][0]), int(points[0][1]), int(points[1][0]), int(points[1][1])
213
+ cv2.rectangle(frame, (x1, y1), (x2, y2), thickness=2,color=(255,0,0),lineType=cv2.LINE_AA)
214
+ label_position = ((x1+x2)//2,(y1+y2)//2) # Adjust the position of the label as needed
215
+ #cv2.putText(frame, str(idx), label_position, cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 1, cv2.LINE_AA)
216
+ name=jpg_path.split("/")[-1]
217
+ cv2.imwrite(save_path+"ordered_"+name,frame)
218
+
219
+
220
+ def intersection_length(x1, x3, x2, x4):
221
+ # 计算两个区间的交集起始点和结束点
222
+ start = max(x1, x2)
223
+ end = min(x3, x4)
224
+
225
+ # 如果交集起始点小于结束点,说明有交集
226
+ if start < end:
227
+ return end - start
228
+ else:
229
+ return 0
230
+
231
+
232
+ def union_length(x1, x3, x2, x4):
233
+ # 计算并集起始点和结束点
234
+ start = min(x1, x2)
235
+ end = max(x3, x4)
236
+
237
+ # 计算并集长度
238
+ union_len = end - start
239
+
240
+ return union_len
241
+
242
+
243
+ def distance_or_intersection(x1, x3, x2, x4):
244
+ # 计算不相交两个区间的最短距离
245
+ distance = min(abs(x1 - x4), abs(x2 - x3))
246
+
247
+ # 判断是否相交
248
+ if intersection_length(x1, x3, x2, x4) > 0:
249
+ return 0 # 区间相交,返回0
250
+ else:
251
+ return distance # 区间不相交,返回最短距离
252
+
253
+
254
+ def union(p1, p2):
255
+ [x1, y1], [x2, y2] = p1
256
+ [x3, y3], [x4, y4] = p2
257
+ lx = min(x1, x3)
258
+ ly = min(y1, y3)
259
+ rx = max(x2, x4)
260
+ ry = max(y2, y4)
261
+ return [[lx, ly], [rx, ry]]
262
+
263
+ def merge_boxes(boxes,thresx=0.7, thresy=2):
264
+
265
+
266
+ boxes = sorted(boxes, key=lambda box: (box[0][1]+box[1][1])/2)
267
+
268
+ now_len=len(boxes)
269
+ for _ in range(10):
270
+ ydis_mean = 0
271
+ for item in boxes:
272
+ [x1, y1], [x3, y3] = item
273
+ ydis_mean += abs(y1 - y3)
274
+ length = len(boxes)
275
+ if length==0:
276
+ break
277
+ ydis_mean /= length
278
+ i = 0
279
+ while i < length:
280
+ j = 0
281
+ # 依次遍历除自身外的全部box
282
+ while j < length:
283
+ mainbox = boxes[i]
284
+ if i == j:
285
+ j += 1
286
+ continue
287
+ length = len(boxes)
288
+ # 算x区间上相交的程度
289
+ intersection = intersection_length(mainbox[0][0], mainbox[1][0], boxes[j][0][0], boxes[j][1][0])
290
+ x_rate = intersection / min(abs(mainbox[0][0] - mainbox[1][0]), abs(boxes[j][0][0] - boxes[j][1][0]))
291
+
292
+ # 算y区间上相远离的程度,使用与字的y间距大小平均值的比值
293
+ y_dis = distance_or_intersection(boxes[i][0][1], boxes[i][1][1], boxes[j][0][1], boxes[j][1][1])
294
+ y_rate = y_dis / ydis_mean
295
+ h1=abs(boxes[i][0][0]-boxes[i][1][0])
296
+ h2=abs(boxes[j][0][0]-boxes[j][1][0])
297
+ l1=abs(boxes[i][0][1]-boxes[i][1][1])
298
+ l2=abs(boxes[j][0][1]-boxes[j][1][1])
299
+ s1=h1*l1
300
+ s2=h2*l2
301
+
302
+ y_rate=y_dis/((l1+l2)/2)
303
+ #print(min(s1,s2)/max(s1,s2))
304
+ if x_rate > thresx and y_rate < thresy:
305
+ rm = boxes[j]
306
+
307
+ u = union(mainbox, rm)
308
+ # 更新第boxes[i],删除被合并的boxes[j]
309
+ boxes[i] = u
310
+ boxes.remove(rm)
311
+ # 处理各个指标的改变
312
+ if j < i:
313
+ i -= 1
314
+ length -= 1
315
+ j -= 1
316
+ j += 1
317
+ i += 1
318
+ if now_len==len(boxes):
319
+ break
320
+ now_len=len(boxes)
321
+ return boxes
322
+
323
+ def merge_boxes_new(boxes):
324
+ boxes = sorted(boxes, key=lambda box: (box[0][1]+box[1][1])/2)
325
+
326
+
327
+ def char2col(jpg_path,boxes):
328
+ columns=merge_boxes(boxes.copy())
329
+ img = cv2.imread(jpg_path)
330
+ h, w, channels = img.shape
331
+
332
+ results={"imageHeight":h,"imageWidth":w,"shapes":[{"points":col} for col in columns]}
333
+ return results