def cal_assignment_fea(assignment, desc): cnt1, cnt2 = assignment[0], assignment[1] arr1 = cv2_transform.cv_cnt_to_np_arr(cnt1) arr2 = cv2_transform.cv_cnt_to_np_arr(cnt2) mask1 = img.build_cnt_mask(arr1) mask2 = img.build_cnt_mask(arr2) fea1 = desc.describe(mask1) fea2 = desc.describe(mask2) return fea1, fea2
def test_smooth_cnt(): cnt1 = np.array([[300, 400, 450, 400, 300, 200, 0, 50, 100, 200], [100, 100, 200, 300, 400, 500, 500, 400, 300, 200]]) # img1 = build_cnt_mask(cnt1) smooth_cnt1 = smooth_cnt(cnt1, sigma=10) smooth_img1 = build_cnt_mask(smooth_cnt1) import matplotlib.pyplot as plt plt.imshow(smooth_img1)
def test_build_cnt_mask(): np_arr = np.array([[10, 40, 50, 40, 20], [10, 20, 30, 40, 30]]) # np_arr = np.array([[10, 25, 30, 10], [10, 15, 30, 30]]) mask = build_cnt_mask(np_arr) # mask = build_cnt_mask(np_arr, mask_size=(100, 100)) # import matplotlib.pyplot as plt # plt.imshow(mask) # plt.show() # import pdb; pdb.set_trace() _ = np.count_nonzero(mask == 255) # calculate the contour area cv_cnt = np_arr_to_cv_cnt(np_arr) _ = get_cnt_area(cv_cnt)
def get_chromosome_shape(chromosome_path, thresh=28): chromosome_name = os.path.splitext(os.path.basename(chromosome_path))[0] karyotype_name = os.path.basename(os.path.dirname(chromosome_path)) ch_img = io.imread(chromosome_path) ch_bin = ch_img > thresh ch_bin = binary_fill_holes(ch_bin) ch_mask = img_as_ubyte(ch_bin) try: _, cnts, _ = cv2.findContours(ch_mask, mode=cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_NONE) except: import pdb pdb.set_trace() refine_cnts = list(filter(lambda x: cv2.contourArea(x) > 48, cnts)) refine_cnts.sort(key=(lambda cnt: np.mean(cnt[:, 0, 0]))) if not (len(refine_cnts) <= 2 and len(refine_cnts) >= 0): print("In {}, the number of contours in {} is {}".format( karyotype_name, chromosome_name, len(refine_cnts))) return None chromosome_desc = {} desc = ZernikeMoments(21) for cur_cnt in refine_cnts: cur_arr = cv2_transform.cv_cnt_to_np_arr(cur_cnt) shape_mask = img.build_cnt_mask(cur_arr) # cur_arr_min_h = np.min(cur_arr[0]) # cur_arr_min_w = np.min(cur_arr[1]) # mask_h, mask_w = shape_mask.shape # sub_img = ch_img[cur_arr_min_h:cur_arr_min_h+mask_h, # cur_arr_min_w:cur_arr_min_w+mask_w] # shift_cnt = cur_cnt.copy() # shift_cnt[:, 0, 0] -= cur_arr_min_w # shift_cnt[:, 0, 1] -= cur_arr_min_h # sub_img3 = np.stack((sub_img, sub_img, sub_img), axis=-1) # cv2.drawContours(sub_img3, [shift_cnt], 0, [127, 0, 0], 2) # io.imsave('boundary.png', sub_img3) cur_fea = desc.describe(shape_mask) shape_name = chromosome_name + '_' + str(uuid.uuid4())[:8] chromosome_desc[shape_name] = list(cur_fea) return chromosome_desc