Tryag File Manager
Home
||
Turbo Force
||
B-F Config_Cpanel
Current Path :
/
paip
/
script
/
unused
/
Or
Select Your Path :
Upload File :
New :
File
Dir
//paip/script/unused/weightAnalyzer.py
import warnings import os import cv2 import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn.cluster import DBSCAN from sklearn.mixture import GaussianMixture as GMM import time from matplotlib.colors import ListedColormap import seaborn as sns import sys if __name__ == '__main__': ''' 1/5...load image : ../data/new_img_6.jpg 2/5...GMM model... 2/5...GMM... : 9.67875599861145 3/5...DB SCAN... 3/5...DB SCAN... : 12.938218832015991 4/5...Image draw 4/5...Image Draw : 14.231426000595093 mean : 101611.5, median : 101611.5, n_detect : 2 exec duration : 14.783560037612915 ''' working_dir = sys.argv[1] if len(sys.argv) > 1 else './' os.chdir(working_dir) default_img = 'new_img_6.jpg' warnings.filterwarnings("ignore") start_time = time.time() # setup n_clusters = 3 low_bound, upper_bound = 20000, 120000 # pixel number of each group data_dir = sys.argv[1] if len(sys.argv) > 1 else '../data/' output_dir = sys.argv[1] if len(sys.argv) > 1 else '../out/' print_time_flag = 0 if len(sys.argv) > 1 else 1 img_name = os.path.basename(sys.argv[2]) if len(sys.argv) > 2 else default_img # load image img = cv2.imread(os.path.join(data_dir, img_name)) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) original_shape = img.shape img2 = img.reshape((-1, 3)) # load palette cmap = ListedColormap(sns.color_palette("tab20")) # print(f'1/5...load image : {os.path.join(data_dir, img_name)}') # print(f'2/5...GMM model...') # GMM g_model = GMM(n_components=n_clusters, covariance_type='tied', random_state=0).fit(img2) # choose 2 of 3 indexes of g_model results g_model_index = np.argsort(g_model.means_[:, 1])[-2:] predicted = g_model.predict(img2) img2_da = img2.copy() img_input = np.append(img2_da, [[x] for x in predicted], axis=1) img_data = pd.DataFrame(img_input.reshape(original_shape[0] * original_shape[1], 4), columns=['r', 'g', 'b', 'gmm']).reset_index() img_data_input = img_data[img_data.gmm.isin(g_model_index)] img_data_input['x'] = img_data_input.index // original_shape[1] img_data_input['y'] = img_data_input.index % original_shape[1] # print(f'2/5...GMM... : {time.time() - start_time}') # print(f'3/5...DB SCAN...') # DB SCAN model = DBSCAN(eps=1., min_samples=5, n_jobs=-1) pred = model.fit_predict(img_data_input[['x', 'y']]) img_data_input['group'] = pred # print(f'3/5...DB SCAN... : {time.time() - start_time}') # pd.dataframe result = pd.DataFrame(img_data_input.groupby('group')['group'].count()[2:]) result.columns = ['cnt'] # group 별 좌표 구하기 grp_list = list(result[result.cnt > low_bound].index) min_max_img_df = img_data_input[img_data_input.group.isin(grp_list)].groupby('group')[['x', 'y']].agg( min_x=('x', 'min'), max_x=('x', 'max'), min_y=('y', 'min'), max_y=('y', 'max'), cnt=('x', 'count') ) min_max_img_df['mat'] = (min_max_img_df.max_x - min_max_img_df.min_x) * ( min_max_img_df.max_y - min_max_img_df.min_y) min_max_img_df['diffs'] = min_max_img_df.mat - min_max_img_df.cnt min_max_img_df['ratio'] = round(min_max_img_df.cnt / min_max_img_df.mat, 1) min_max_img_df = min_max_img_df.reset_index() # pixel cnt... image boundary min_max_img_df = min_max_img_df[ (min_max_img_df.cnt > low_bound) & (min_max_img_df.cnt < upper_bound) & # pixel cnt filter (min_max_img_df.min_x > 0) & # point filter below 4 lines (min_max_img_df.min_y > 0) & (min_max_img_df.max_x < original_shape[0] - 1) & (min_max_img_df.max_y < original_shape[1] - 1)] # group candi final_group_candi = min_max_img_df.group.unique() # replce to white color of each pixel which is in group candi img_data_input = img_data_input[img_data_input.group.isin(min_max_img_df.group.unique())] ''' img_cp = img.copy() for x in img_data_input[['x', 'y', 'group']].iterrows(): # print(x) x_ind, y_ind, grp_ind = x[1]['x'], x[1]['y'], x[1]['group'] if grp_ind in grp_list: img_cp[x_ind, y_ind] = tuple(int(y * 255) for y in cmap(grp_ind % cmap.N)[:-1]) ''' # print(f'4/5...Image draw') img_cp = img.copy() calib_list = [] for x in min_max_img_df.iterrows(): # print(x) # bound x_min, x_max, y_min, y_max, grp_ind = int(x[1]['min_x']), int(x[1]['max_x']), int(x[1]['min_y']), int( x[1]['max_y']), int(x[1]['group']) map_color = tuple(y * 255 for y in cmap(grp_ind % cmap.N)[:-1]) inner_list = img_data_input[img_data_input.group == grp_ind][['x', 'y']] for xxx, yyy in inner_list.values.tolist(): img_cp[xxx, yyy] = map_color region_img = img_cp[x_min:x_max, y_min:y_max].copy() x_ind, y_ind = region_img.shape[:2] for x in range(x_ind): for y in range(y_ind): if all(region_img[x, y] == map_color): region_img[x, y] = (255, 255, 255) gray = cv2.cvtColor(region_img, cv2.COLOR_RGB2GRAY) ret, binary = cv2.threshold(gray, 254, 255, cv2.THRESH_BINARY) # thr1 = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 5, 2) # binary = cv2.bitwise_not(binary) contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # print(f'length of contours : {len(contours)}') region_img_con = region_img.copy() # region_img_con = cv2.drawContours(region_img_con, [contours[0]], 0, (0, 0, 255), 2) # region_img_con = cv2.putText(region_img_con, str(i), tuple(contours[0][0][0]), cv2.FONT_HERSHEY_COMPLEX, 0.8, (0, 255, 0), 1) region_img_after = region_img.copy() region_img_after = cv2.fillPoly(region_img_after, pts=contours, color=map_color) shapes = region_img.shape white_list = [(x, y) for x in range(shapes[0]) for y in range(shapes[1]) if all(region_img_after[x, y] == map_color)] calib_list.append(len(white_list)) ''' f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9)) f.tight_layout() ax1.imshow(region_img) ax1.set_title('Original Image', fontsize=50) ax2.imshow(region_img_after) ax2.set_title('clustered Image', fontsize=50) plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.) img_cp[x_min:x_max, y_min:y_max] = region_img_after ''' img_cp = cv2.rectangle(img_cp, (y_min, x_min), (y_max, x_max), (0, 255, 0), 3) img_cp = cv2.putText(img_cp, f'{len(white_list)}', (y_min, x_max + 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 3) # mean value min_max_img_df['calib_cnt'] = calib_list min_max_img_df['new_ratio'] = round(min_max_img_df['calib_cnt'] / min_max_img_df['mat'], 1) img_cp = cv2.putText(img_cp, f'mean : {min_max_img_df.calib_cnt.mean()}, median : {min_max_img_df.calib_cnt.median()}, n_detect : {len(min_max_img_df)}', (5, original_shape[0] - 5), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 0, 0), 2) # plt.imshow(img_cp) # print(f'4/5...Image Draw : {time.time() - start_time}') # put text :: mean value # plot image f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9)) f.tight_layout() ax1.imshow(img) ax1.set_title('Original Image', fontsize=50) ax2.imshow(img_cp) ax2.set_title('clustered Image', fontsize=50) plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.) # 이미지 저장 : result_<<원 이미지 파일 이름>> f.savefig(os.path.join(output_dir, 'result_' + img_name)) # console out print( f'mean : {min_max_img_df.calib_cnt.mean()}, median : {min_max_img_df.calib_cnt.median()}, n_detect : {len(min_max_img_df)}') # test용 print if print_time_flag : print(f'exec duration : {time.time() - start_time}')