|
11 | 11 | from scipy import fftpack
|
12 | 12 | import copy
|
13 | 13 | import pywt
|
14 | | -from sklearn.decomposition import FastICA, KernelPCA, PCA |
| 14 | +from skimage.measure import moments |
| 15 | +from skimage.filters import threshold_otsu, gaussian |
| 16 | +from skimage.color import rgb2gray |
| 17 | +from skimage.morphology import remove_small_objects |
| 18 | + |
| 19 | +# from sklearn.decomposition import FastICA, KernelPCA, PCA |
| 20 | + |
| 21 | + |
| 22 | +def autocrop(img, min_size=30, convert_gray=False, extra_space=0.2): |
| 23 | + """Separate front ground and background. Choose only largest objects as front ground. |
| 24 | + |
| 25 | + min_size: minimum size in pixels of objects to include. |
| 26 | + extra_space: fraction of the front ground size |
| 27 | + """ |
| 28 | + img = np.array(img).copy() |
| 29 | + # Convert to grayscale if RGB |
| 30 | + if len(img.shape) > 2: |
| 31 | + img_gr = rgb2gray(img) |
| 32 | + else: |
| 33 | + img_gr = img.copy() |
| 34 | + |
| 35 | + # Filter image |
| 36 | + img_gr = gaussian(img_gr) |
| 37 | + |
| 38 | + # Convert to binary |
| 39 | + thr = threshold_otsu(img_gr) |
| 40 | + binary = img_gr > thr |
| 41 | + |
| 42 | + # Remove small spots |
| 43 | + binary = remove_small_objects(binary, min_size=min_size) |
| 44 | + |
| 45 | + # Find centroid |
| 46 | + M = moments(binary) |
| 47 | + centroid = (M[1, 0] / M[0, 0], M[0, 1] / M[0, 0]) |
| 48 | + |
| 49 | + # Find edges |
| 50 | + fg_indices = np.argwhere(binary > 0) |
| 51 | + mincol = np.min(fg_indices[:, 1]) |
| 52 | + maxcol = np.max(fg_indices[:, 1]) |
| 53 | + minrow = np.min(fg_indices[:, 0]) |
| 54 | + maxrow = np.max(fg_indices[:, 0]) |
| 55 | + extension = extra_space * np.array([maxrow - minrow, maxcol - mincol]) |
| 56 | + |
| 57 | + # Crop to 100% + extra_space length each dimension |
| 58 | + framerow = np.clip( |
| 59 | + [int(minrow - extension[0]), int(maxrow + extension[0])], |
| 60 | + a_min=0, |
| 61 | + a_max=img.shape[0], |
| 62 | + ) |
| 63 | + framecol = np.clip( |
| 64 | + [int(mincol - extension[1]), int(maxcol + extension[1])], |
| 65 | + a_min=0, |
| 66 | + a_max=img.shape[1], |
| 67 | + ) |
| 68 | + |
| 69 | + if convert_gray: |
| 70 | + return rgb2gray( |
| 71 | + img[framerow[0] : framerow[1], framecol[0] : framecol[1]] |
| 72 | + ) |
| 73 | + else: |
| 74 | + return img[framerow[0] : framerow[1], framecol[0] : framecol[1]] |
15 | 75 |
|
16 | 76 |
|
17 | 77 | def destripe_by_wavelet_svd(img, wavelet="sym7", level=None, vecnum=None):
|
|
0 commit comments