|
a |
|
b/drunet/utils.py |
|
|
1 |
import os |
|
|
2 |
import time |
|
|
3 |
import math |
|
|
4 |
import pathlib |
|
|
5 |
from functools import reduce |
|
|
6 |
from collections import Counter |
|
|
7 |
|
|
|
8 |
import cv2 as cv |
|
|
9 |
import numpy as np |
|
|
10 |
import pandas as pd |
|
|
11 |
from tqdm import tqdm |
|
|
12 |
import matplotlib.pyplot as plt |
|
|
13 |
|
|
|
14 |
|
|
|
15 |
def get_path(file_dir): |
|
|
16 |
path_list = [] |
|
|
17 |
name_list = [] |
|
|
18 |
for path in pathlib.Path(file_dir).iterdir(): |
|
|
19 |
path_list.append(str(path)) |
|
|
20 |
name_list.append(path.name) |
|
|
21 |
path_list = sorted(path_list, key=lambda path_: int(pathlib.Path(path_).stem)) |
|
|
22 |
name_list = sorted(name_list, key=lambda path_: int(pathlib.Path(path_).stem)) |
|
|
23 |
return path_list, name_list |
|
|
24 |
|
|
|
25 |
|
|
|
26 |
def check_file(paths): |
|
|
27 |
if type(paths) is not list: |
|
|
28 |
paths = [paths] |
|
|
29 |
for path in paths: |
|
|
30 |
if not os.path.exists(path): |
|
|
31 |
os.makedirs(path) |
|
|
32 |
return |
|
|
33 |
|
|
|
34 |
|
|
|
35 |
def list_file(dir_path): |
|
|
36 |
paths = [] |
|
|
37 |
for path in pathlib.Path(dir_path).iterdir(): |
|
|
38 |
paths.append(str(path)) |
|
|
39 |
return paths |
|
|
40 |
|
|
|
41 |
|
|
|
42 |
def crop_image(read_dir, save_dir, o_w, o_h, r_w, r_h, split=False): |
|
|
43 |
if not os.path.exists(save_dir): |
|
|
44 |
os.makedirs(save_dir) |
|
|
45 |
|
|
|
46 |
# Crop large images into small images |
|
|
47 |
i = 0 |
|
|
48 |
file_paths_list = get_file_path(read_dir) |
|
|
49 |
for file_path in file_paths_list: |
|
|
50 |
for row in range(o_h // r_h): |
|
|
51 |
for col in range(o_w // r_w): |
|
|
52 |
img = cv.imread(file_path) |
|
|
53 |
cropped = img[row * r_h: (row + 1) * r_h, col * r_w: (col + 1) * r_w, :] |
|
|
54 |
|
|
|
55 |
if split: |
|
|
56 |
save_path = os.path.join(save_dir, str(pathlib.Path(file_path).stem)) |
|
|
57 |
if not os.path.exists(save_path): |
|
|
58 |
os.makedirs(save_path) |
|
|
59 |
cv.imwrite(os.path.join(save_path, '{}.jpg'.format(i)), cropped) |
|
|
60 |
else: |
|
|
61 |
cv.imwrite(os.path.join(save_dir, '{}.jpg'.format(i)), cropped) |
|
|
62 |
i += 1 |
|
|
63 |
print('Cropped image is complete!') |
|
|
64 |
return |