crop.py
1.47 KB
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
__author__ = 'chunk'
import os, sys
from PIL import Image
from ..common import *
import random
import cv2
import numpy as np
base_dir = '/data/hadoop/ImageNet/ILSVRC/ILSVRC2013_DET_val/'
category = 'Test'
def crop_Test():
for path, subdirs, files in os.walk(os.path.join(base_dir, category)):
for name in files:
image = os.path.join(path, name)
print image
# try:
# im = Image.open(image)
# w, h = im.size
# if w < 300 or h < 300:
# continue
# left, upper = random.randint(0, w - 300), random.randint(0, h - 300)
# im = im.crop((left, upper, left + 300, upper + 300))
# im.save(os.path.join(base_dir, category + '_crop_pil', name))
# except:
# pass
try:
img = cv2.imread(image, cv2.CV_LOAD_IMAGE_UNCHANGED)
h, w = img.shape[:2]
if w < 300 or h < 300:
continue
left, upper = random.randint(0, w - 300), random.randint(0, h - 300)
img_crop = img[upper:upper + 300, left:left + 300]
cv2.imwrite(os.path.join(base_dir, category + '_crop_cv', name), img_crop)
except Exception as e:
print '[EXCPT]', e
pass
if __name__ == '__main__':
timer = Timer()
timer.mark()
crop_Test()
timer.report()
pass