-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcrop_img.py
62 lines (41 loc) · 1.31 KB
/
crop_img.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import os
import shutil
from os.path import join
import cv2
import glob
root_dir = "./fruit_image"
save_dir = "./bbox"
jpg_list = glob.glob(root_dir + "/*.jpg")
fo = open("dpj_small.txt", "w")
max_s = -1
min_s = 1000
for jpg_path in jpg_list:
# jpg_path = jpg_list[3]
txt_path = jpg_path.replace("jpg", "txt")
jpg_name = os.path.basename(jpg_path)
f = open(txt_path, "r")
img = cv2.imread(jpg_path)
height, width, channel = img.shape
file_contents = f.readlines()
for num, file_content in enumerate(file_contents):
print(num)
clss, xc, yc, w, h = file_content.split()
xc, yc, w, h = float(xc), float(yc), float(w), float(h)
xc *= width
yc *= height
w *= width
h *= height
max_s = max(w*h, max_s)
min_s = min(w*h, min_s)
half_w, half_h = w // 2, h // 2
x1, y1 = int(xc - half_w), int(yc - half_h)
x2, y2 = int(xc + half_w), int(yc + half_h)
crop_img = img[y1:y2, x1:x2]
new_jpg_name = jpg_name.split('.')[0] + "_crop_" + str(num) + ".jpg"
cv2.imwrite(os.path.join(save_dir, new_jpg_name), crop_img)
# cv2.imshow("croped",crop_img)
# cv2.waitKey(0)
fo.write(os.path.join(save_dir, new_jpg_name)+"\n")
f.close()
fo.close()
print(max_s, min_s)