-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrop.py
92 lines (84 loc) · 3.58 KB
/
crop.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# -*- coding: utf-8 -*-
import os
import cv2
import json
#import numpy as np
'''滑动窗口'''
def sliding_window(item_name,
image,
step_size,
window_size,
width,
height,
shrink_ratio,
save_path='sub_imgs/'):
count = 0
info_list = []
for y in range(0, image.shape[0], step_size[1]):
for x in range(0, image.shape[1], step_size[0]):
if (y + window_size[1]) <= height and (
x + window_size[0]) <= width: #没超出下边界,也超出下边界
slide = image[y:y + window_size[1], x:x + window_size[0], :]
# slide_shrink = cv2.resize(slide, window_size, interpolation=cv2.INTER_AREA)
#slide_shrink_gray = cv2.cvtColor(slide_shrink,cv2.COLOR_BGR2GRAY)
sub_image_name = item_name.split('.')[0] + '_' + str(
count) + '.jpg'
cv2.imwrite(save_path + sub_image_name, slide)
info_list.append({
'image_name':
item_name,
'sub_image_name':
sub_image_name,
'offset': [x, y],
'shrink_ratio': [shrink_ratio[0], shrink_ratio[1]]
})
count = count + 1 #count持续加1
if (y + window_size[1]) > height and (
x +
window_size[0]) > width: #超出右边界,但没超出下边界 或者 超出下边界,但没超出右边界
continue
if (y + window_size[1]) > height and (
x + window_size[0]) <= width: #超出下边界,也超出下边界
break
return info_list
def crop(path, item_name, step_ratio=0.7, window_size=[512, 512], save_path='sub_imgs/'):
step_size = (int(round(step_ratio * window_size[0])),
int(round(step_ratio * window_size[1]))) #步长就是0.7倍的滑窗大小
image = cv2.imread(path + item)
height, width = image.shape[0], image.shape[1]
new_size = (int(round(width / step_size[0] - 2) * step_size[0]) +
window_size[0],
int(round(height / step_size[1] - 2) * step_size[1]) +
window_size[1])
img_shrink = cv2.resize(image, new_size,
interpolation=cv2.INTER_AREA) #改变图像大小
shrink_ratio = (image.shape[1] / img_shrink.shape[1],
image.shape[0] / img_shrink.shape[0])
info_list = sliding_window(item_name, img_shrink, step_size, window_size,
img_shrink.shape[1], img_shrink.shape[0],
shrink_ratio, save_path)
return info_list
if __name__ == "__main__":
result_list = []
path = 'test/' #文件路径
save_path='sub_imgs/'
filelist = os.listdir(path) # 列举图片名
cnt = 0
num = 1
sub_imgs_num = 0
if not os.path.exists(save_path+'/'+str(num)+'/'):
os.makedirs(save_path+'/'+str(num)+'/')
for item in filelist:
print(cnt)
info_list = crop(path, item, save_path=save_path+'/'+str(num)+'/')
sub_imgs_num += len(info_list)
# print(sub_imgs_num)
result_list.extend(info_list)
cnt += 1
if sub_imgs_num >= 10000:
num += 1
if not os.path.exists(save_path+'/'+str(num)+'/'):
os.makedirs(save_path+'/'+str(num)+'/')
sub_imgs_num = 0
with open("info.json", 'w') as f:
json.dump(result_list, f, indent=4)