Пример #1
0
def step2(cell_id):

    print("============Step 2 Start============")

    img = cv.imread(
        "G:\\2020summer\\Project\\Cell_classfication_1.0.0\\temp_1.bmp")
    img_result = img.copy()
    #img=cv.cvtColor(img,cv.COLOR_BGR2BGRA)

    #-----preprocess-----
    gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    #cv.imshow("gray", gray)

    gauss = cv.GaussianBlur(gray, (5, 5), 5)

    #cv.imshow("gauss1",gauss)
    #print("gauss_test: ",gauss[361][616])
    '''
    x_sample = :  616
    y_sample = :  361
    '''
    img_shape = gauss.shape

    # read from local
    f = open("G:\\2020summer\\Project\\Cell_classfication_1.0.0\\dict.txt",
             'r')
    dict_ = eval(f.read())
    f.close()

    # distance from single point to center
    distance_from_single_point_to_center_list = []
    for m in range(cell_id, cell_id + 1):
        x_sample = dict_[m][0]
        y_sample = dict_[m][1]
        angle_temp_list = angle_round(x_sample, y_sample, 65)  # 第三个参数为圆的半径

        for i in range(1, 73):
            x1 = angle_temp_list[i - 1][0]
            y1 = angle_temp_list[i - 1][1]
            cx = x_sample
            cy = y_sample
            temp_list = pixel_between_two_points(cx, round(x1), cy, round(y1))
            #print(len(temp_list))
            ray_lenth = 0
            compare_distance_value = 0
            compare_color_value = 255
            color_hist = []
            #单条射线的所有点,颜色深度的集合,找出前三名
            color_deep_rank = {}
            for m in range(0, len(temp_list)):
                x_temp = temp_list[m][0]
                y_temp = temp_list[m][1]

                single_lenth = cell_wall_ray_lenth(cx, cy, x_temp, y_temp)

                color_deep_rank[y_temp, x_temp] = gauss[y_temp][x_temp]

                sorted_color_deep_rank = sorted(color_deep_rank.items(),
                                                key=lambda kv: (kv[1], kv[0]),
                                                reverse=False)

                if gauss[y_temp][x_temp] <= compare_color_value:
                    compare_color_value = gauss[y_temp][x_temp]
                    compare_distance_valuevalue = single_lenth

                    x_final = x_temp
                    y_final = y_temp
                else:
                    pass
                #==hist graph
                color_hist.append(gauss[y_temp][x_temp])

            #print("**************** test: compare_color_value: ", compare_color_value,"dic rank: ", sorted_color_deep_rank[0],sorted_color_deep_rank[1],sorted_color_deep_rank[2])
            #plt.plot(color_hist, color="black")
            #plt.show()
            cv.circle(img, (round(x_final), round(y_final)), 1, (0, 0, 255),
                      -1)

            #cv.circle(img, (round(sorted_color_deep_rank[1][0][1]), round(sorted_color_deep_rank[1][0][0])), 1, (0, 255, 255), -1)
            #cv.circle(img, (round(sorted_color_deep_rank[2][0][1]), round(sorted_color_deep_rank[2][0][0])), 1, (0, 255, 255), -1)
            #cv.circle(img, (round(sorted_color_deep_rank[3][0][1]), round(sorted_color_deep_rank[3][0][0])), 1,(0, 255, 255), -1)
            #cv.circle(img, (round(sorted_color_deep_rank[4][0][1]), round(sorted_color_deep_rank[4][0][0])), 1,(0, 255, 255), -1)
            #fixed_data_list = un_angle_round(x_sample,y_sample,fixed_data)
            #cv.circle(img, (round(fixed_data_list[i-1][0]), round(fixed_data_list[i-1][1])), 1, (0, 255, 255), -1)
            #cv.circle(img, (round(x1), round(y1)), 1, (255, 0, 255), -1) #半径显示

            #distance test and upload
            distance_from_single_point_to_center_list.append(
                distance(x_final, y_final, cx, cy))
        #<data_clean

        # data_clean>
        #< list save
        file = open('test_list.txt', 'w')
        for fp in distance_from_single_point_to_center_list:
            file.write(str(fp))
            file.write('\n')
        file.close()
        #list save >

        from k_means_1D import k_means_1d_def
        #temp_list_1=k_means_1d_def(3,30)[2]
        #plt.plot([temp_list_1[0]]*len(a), color="red", linestyle='--')
        #plt.plot([temp_list_1[1]] * len(a), color="red", linestyle='--')

        #plt.show()

    #cv.imshow("img_test_round", img)
    cv.imwrite(
        "G:\\2020summer\\Project\\Cell_classfication_1.0.0\\step2_output.bmp",
        img)

    print("============Step 2 End / Dataset Saved============")
    cv.waitKey()
def step5(cell_id, total_cells_number, output_not_circle):

    img = cv.imread("bin\\temp_1.bmp")
    if cell_id == 1:
        cv.imwrite("bin\\output\\temp_display.bmp", img)
    display = cv.imread("bin\\output\\temp_display.bmp")

    # -----preprocess-----
    gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    # cv.imshow("gray", gray)

    gauss = cv.GaussianBlur(gray, (5, 5), 5)

    img_shape = gauss.shape

    # read from local
    f = open("bin\\dict.txt", 'r')
    dict_ = eval(f.read())
    f.close()
    #print("read from local : ", dict_)
    # distance from single point to center
    distance_from_single_point_to_center_list = []

    for m in range(cell_id, cell_id + 1):  # 对某些点进行测试# 28上一次测试的
        # <input
        file1 = open('bin\\data_smooth_output.txt', 'r')
        fixed_data = [float(x.strip()) for x in file1]
        file1.close()

        # input>

        x_sample = dict_[m][0]
        y_sample = dict_[m][1]
        angle_temp_list = angle_round(x_sample, y_sample, 65)  # 第三个参数为圆的半径

        for i in range(1, 73):
            x1 = angle_temp_list[i - 1][0]
            y1 = angle_temp_list[i - 1][1]
            cx = x_sample
            cy = y_sample
            temp_list = pixel_between_two_points(cx, round(x1), cy, round(y1))

            ray_lenth = 0
            compare_distance_value = 0
            compare_color_value = 255
            color_hist = []
            # 单条射线的所有点,颜色深度的集合,找出前三名
            color_deep_rank = {}
            for m in range(0, len(temp_list)):
                x_temp = temp_list[m][0]
                y_temp = temp_list[m][1]

                single_lenth = cell_wall_ray_lenth(cx, cy, x_temp, y_temp)

                color_deep_rank[y_temp, x_temp] = gauss[y_temp][x_temp]

                sorted_color_deep_rank = sorted(color_deep_rank.items(),
                                                key=lambda kv: (kv[1], kv[0]),
                                                reverse=False)

                if gauss[y_temp][x_temp] <= compare_color_value:
                    compare_color_value = gauss[y_temp][x_temp]
                    compare_distance_valuevalue = single_lenth

                    x_final = x_temp
                    y_final = y_temp
                else:
                    pass
                # ==hist graph
                color_hist.append(gauss[y_temp][x_temp])

            #print("**************** test: compare_color_value: ", compare_color_value, "dic rank: ",sorted_color_deep_rank[0], sorted_color_deep_rank[1], sorted_color_deep_rank[2])
            # plt.plot(color_hist, color="black")
            # plt.show()
            #cv.circle(display, (round(x_final), round(y_final)), 1, (0, 0, 255), -1)
            # cv.circle(img, (round(sorted_color_deep_rank[1][0][1]), round(sorted_color_deep_rank[1][0][0])), 1, (0, 255, 255), -1)
            # cv.circle(img, (round(sorted_color_deep_rank[2][0][1]), round(sorted_color_deep_rank[2][0][0])), 1, (0, 255, 255), -1)
            fixed_data_list = un_angle_round(x_sample, y_sample, fixed_data)
            #print(fixed_data_list)
            cv.circle(display, (round(
                fixed_data_list[i - 1][0]), round(fixed_data_list[i - 1][1])),
                      1, (0, 255, 0), -1)
            #cv.circle(display, (round(x1), round(y1)), 1, (255, 0, 255), -1)  # 半径显示

            # distance test and upload
            distance_from_single_point_to_center_list.append(
                distance(x_final, y_final, cx, cy))

        standard_r = math.ceil(mean(fixed_data))
        standard_error = 0
        for i in range(0, 72):
            standard_error += abs(fixed_data[i] - standard_r)

        area_calculate_from_points(fixed_data_list)
        #holo_area_calculate_from_points(fixed_data_list,gray,200)

        plt.show()
        #mean of r
        cv.circle(display, (x_sample, y_sample), math.ceil(standard_r),
                  (0, 0, 255), 0)
        #print("not circle degree is: ",format(((standard_error/72)/standard_r),'.2%'))
        output_not_circle.append(round(((standard_error / 72) / standard_r)))
        #=========nucleus=======
        file1 = open('bin\\area_of_nucleus.txt', 'r')
        dataset1 = [float(x.strip()) for x in file1]
        file1.close()
        # print("The area of cell nucleus is: ",round(dataset1[cell_id-1]))
    if cell_id <= total_cells_number:
        cv.putText(display, "Chromophobe Kidney Cancer Test", (80, 30),
                   cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1)

        cv.putText(display, "- If the Result Value is less than 0,",
                   (80, img.shape[0] - 110), cv.FONT_HERSHEY_SIMPLEX, 0.5,
                   (0, 0, 0), 1)
        cv.putText(
            display,
            "then there is a high probability that the image is Chromophobe.",
            (80, img.shape[0] - 90), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0),
            1)
        cv.putText(display, "- If the non-circle value is less than 0.24,",
                   (80, img.shape[0] - 70), cv.FONT_HERSHEY_SIMPLEX, 0.5,
                   (0, 0, 0), 1)
        cv.putText(
            display,
            "then there is a high probability that the image is Chromophobe.",
            (80, img.shape[0] - 50), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0),
            1)
        cv.putText(display, "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
                   (80, img.shape[0] - 30), cv.FONT_HERSHEY_SIMPLEX, 0.5,
                   (0, 0, 0), 1)
    #cv.imshow("step4 output", display)

    cv.imwrite("bin\\output\\temp_display.bmp", display)
                       cv.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
        except:
            pass
        if counter_number == 40:
            x1 = cX
            y1 = cY
        if counter_number == 36:
            x2 = cX
            y2 = cY
        #cv.drawContours(img_masked, [cnts[i]], -1, (255, 255, 255), -1)#mask contours
#-----put Text-----
print("total cells number : ", counter_number)

cv.line(img_masked, (x1, y1), (x2, y2), (0, 0, 255), 2)

list_of_two_points = pixel_between_two_points(x1, x2, y1, y2)
print(list_of_two_points)

#-----output information on the line
height_of_two_points = []
height_of_two_points_B = []
height_of_two_points_G = []
height_of_two_points_R = []

for m in range(0, len(list_of_two_points)):
    height = img[list_of_two_points[m][1], list_of_two_points[m][0]]
    try:
        height_B = img[list_of_two_points[m][1], list_of_two_points[m][0]][0]
        height_G = img[list_of_two_points[m][1], list_of_two_points[m][0]][1]
        height_R = img[list_of_two_points[m][1], list_of_two_points[m][0]][2]
        height_of_two_points_B.append(height_B)
Пример #4
0
def step1():
    cell_area_hist_list = []
    print("============Step 1 Start============")
    # 初始化

    path = 'G:\\2020summer\\Project\\Cell_classfication_1.0.0\\Single_Cell'
    for i in os.listdir(path):
        path_file = os.path.join(path, i)
        if os.path.isfile(path_file):
            os.remove(path_file)
        else:
            for f in os.listdir(path_file):
                path_file2 = os.path.join(path_file, f)
                if os.path.isfile(path_file2):
                    os.remove(path_file2)

    #-----read-----
    root = tk.Tk()
    root.withdraw()

    file_path = filedialog.askopenfilename()
    #img=cv.imread("G:\\2020summer\\Project\\Chromophobe_dataset1\\4.jpg")
    img = cv.imread(file_path)
    img_original = img
    print("Img size: [Width :", img.shape[0], "]", "[Height :", img.shape[1],
          "]")

    img = cv.copyMakeBorder(img,
                            80,
                            450,
                            60,
                            60,
                            cv.BORDER_CONSTANT,
                            value=[255, 255, 255])
    #img=cv.cvtColor(img,cv.COLOR_BGR2BGRA)

    img_masked = img.copy()
    img_nucleus_white_img = img.copy()

    #-----preprocess-----
    gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    #cv.imshow("gray", gray)

    gauss = cv.GaussianBlur(gray, (5, 5), 5)
    #cv.imshow("gauss1",gauss)

    ret, thresh = cv.threshold(gauss, 190, 255, 0)
    cv.imwrite(
        "G:\\2020summer\\Project\\Chromophobe_dataset1\\figure3_left.jpg",
        thresh)
    #cv.imshow("thresh",thresh)

    erode = cv.erode(thresh, None, iterations=1)
    #cv.imshow("erode",erode)

    #-----remove outlines-----

    #cv.imshow("erode",erode)
    for i in range(0, img.shape[0]):
        for j in range(0, img.shape[1]):
            erode[0][j] = 255
    #-----find contours-----
    cnts, hierarchy = cv.findContours(erode.copy(), cv.RETR_LIST,
                                      cv.CHAIN_APPROX_NONE)

    def cnt_area(cnt):
        area = cv.contourArea(cnt)
        return area

    counter_number = 0
    location_cells_center = {}
    area_of_cells_nucleus = []
    Whole_pic_cell_area_ave_percent = []
    Whole_pic_cell_color_ave = []
    for i in range(0, len(cnts)):
        if 250 <= cnt_area(cnts[i]) <= 0.2 * (img.shape[0] * img.shape[1]):

            cell_area_hist_list.append(cnt_area(cnts[i]))
            #print(cnts[i])
            #cell_area_hist_list.append(area_calculate_from_points(cnts[i]))
            counter_number += 1
            #print(cnts[i])
            #print("======")
            cv.drawContours(img_masked, cnts[i], -1, (0, 0, 255),
                            2)  #draw contours
            cv.drawContours(img_nucleus_white_img, [cnts[i]], -1,
                            (255, 255, 255), -1)  #masked white
            M = cv.moments(cnts[i])

            #检索每个细胞的内部颜色
            x, y, w, h = cv.boundingRect(cnts[i])

            #cv.imshow('single_cell', newimage)

            cell_area_percent = 0

            for row in range(y, y + h):
                for col in range(x, x + w):
                    result = cv.pointPolygonTest(cnts[i], (col, row), False)
                    if result == -1:

                        cv.circle(gray, (col, row), 1, 255, -1)
                        cv.circle(img, (col, row), 1, (255, 255, 255), -1)
                        cell_area_percent += 1
            cv.rectangle(img, (x, y), (x + w, y + h), (153, 153, 0), 1)
            newimage_gray = gray[y:y + h, x:x + w]
            cv.imwrite(
                "G:\\2020summer\\Project\\Cell_classfication_1.0.0\\Single_Cell\\"
                + str(counter_number) + ".jpg", newimage_gray)
            Single_Cell_Color_Distrution = []
            for row in range(h):
                for col in range(w):
                    if newimage_gray[row, col] != 255:
                        Single_Cell_Color_Distrution.append(newimage_gray[row,
                                                                          col])
            '''
            plt.hist(Single_Cell_Color_Distrution,bins=50)
            plt.title(str(counter_number))
            plt.show()
            '''
            #print("this cell area percent= ",str(cell_area_percent/(w*h)))
            numpy.set_printoptions(precision=3)
            Whole_pic_cell_area_ave_percent.append(cell_area_percent / (w * h))
            Whole_pic_cell_color_ave.append(
                numpy.mean(Single_Cell_Color_Distrution))
            """#找出masked细胞内点的坐标
            rect = cv.minAreaRect(cnts[i])
            cx, cy = rect[0]
            box = cv.boxPoints(rect)
            box = np.int0(box)
            cv.drawContours(img_masked, [box], 0, (0, 0, 255), 2)
            #cv.circle(img_masked, (np.int32(cx), np.int32(cy)), 2, (255, 0, 0), 2, 8, 0)

            box_gray_color=[]
            for by in range(box[2][1],box[0][1]+1):
                for bx in range(box[1][0],box[3][0]+1):
                    #print(bx,by)
                    #cv.circle(img_masked,(bx, by), 1, (255, 0, 0), 2, 8, 0)
                    box_gray_color.append(gray[bx,by])
            plt.hist(box_gray_color)

            plt.hist(box_gray_color,bins=50)
            plt.title(str(counter_number))
            plt.show()

            dist=cv.pointPolygonTest(cnts[i],(50,50),True)
            """
            try:
                cX = int(M["m10"] / M["m00"])
                cY = int(M["m01"] / M["m00"])
                cv.circle(img_masked, (cX, cY), 3, (255, 255, 255), -1)
                cv.putText(img_masked, str(counter_number), (cX - 20, cY - 20),
                           cv.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
                area_of_cells_nucleus.append(cnt_area(cnts[i]))
                location_cells_center[counter_number] = [cX, cY]
            except:
                pass
            if counter_number == 1:
                x1 = cX
                y1 = cY
            if counter_number == 2:
                x2 = cX
                y2 = cY
            if counter_number == 20:
                x_sample = cX
                y_sample = cY

            #cv.drawContours(img_masked, [cnts[i]], -1, (255, 255, 255), -1)#mask contours
    print("Whole pic average cell nucleus area percent: ",
          Whole_pic_cell_area_ave_percent)
    print("Whole pic average cell nucleus area percent_ave: ",
          numpy.mean(Whole_pic_cell_area_ave_percent))
    print("Whole pic average cell nucleus color deep percent: ",
          Whole_pic_cell_color_ave)
    print("Whole pic average cell nucleus color deep percent_ave: ",
          numpy.mean(Whole_pic_cell_color_ave))
    cv.imshow('single_cell', img)
    #-----put Text-----
    print("total cells number : ", counter_number)

    #cv.line(img_masked, (x1,y1), (x2,y2), (0,0,255), 2)

    list_of_two_points = pixel_between_two_points(x1, x2, y1, y2)

    #-----output information on the line
    height_of_two_points = []
    height_of_two_points_B = []
    height_of_two_points_G = []
    height_of_two_points_R = []

    for m in range(0, len(list_of_two_points)):
        height = img[list_of_two_points[m][1], list_of_two_points[m][0]]
        try:
            height_B = img[list_of_two_points[m][1],
                           list_of_two_points[m][0]][0]
            height_G = img[list_of_two_points[m][1],
                           list_of_two_points[m][0]][1]
            height_R = img[list_of_two_points[m][1],
                           list_of_two_points[m][0]][2]
            height_of_two_points_B.append(height_B)
            height_of_two_points_G.append(height_G)
            height_of_two_points_R.append(height_R)
        except:
            pass
        #print(height)
        height_of_two_points.append(height)
    img_sample = img.copy()
    cv.circle(img_sample, (x_sample, y_sample), 3, (0, 0, 255), -1)
    font = cv.FONT_HERSHEY_SIMPLEX
    cv.putText(img_sample, "Sample_Point", (x_sample - 20, y_sample - 20),
               font, 0.7, (255, 255, 255), 2)
    #cv.imshow("img_sample_location_RED_DOT", img_sample)

    # save to local
    f = open("G:\\2020summer\\Project\\Cell_classfication_1.0.0\\dict.txt",
             'w')
    f.write(str(location_cells_center))
    f.close()

    # < list save
    file1 = open('area_of_nucleus.txt', 'w')
    for fp in area_of_cells_nucleus:
        file1.write(str(fp))
        file1.write('\n')
    file1.close()
    # list save >

    cv.imwrite("G:\\2020summer\\Project\\Cell_classfication_1.0.0\\temp.bmp",
               img_masked)
    cv.imwrite("G:\\2020summer\\Project\\Cell_classfication_1.0.0\\temp_1.bmp",
               img_nucleus_white_img)
    cv.imwrite(
        "G:\\2020summer\\Project\\Chromophobe_dataset1\\figure3_right.jpg",
        img_masked)
    #================hist of cells area==================
    #plt.hist(cell_area_hist_list)
    #plt.show()

    #=================================
    #-----
    #=================================UI/
    cv.putText(img_masked, "Overview", (80, 40), cv.FONT_HERSHEY_SIMPLEX, 1,
               (0, 0, 0), 2)
    image_size_text = "Image size: [Width :" + str(
        img_original.shape[0]) + "]" + "[Height :" + str(
            img_original.shape[1]) + "]"
    cv.putText(img_masked, image_size_text, (80, img.shape[0] - 400),
               cv.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 2)
    cv.putText(img_masked, "Total cells number: " + str(counter_number),
               (80, img.shape[0] - 350), cv.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0),
               2)
    cv.putText(img_masked, "Close window to continue",
               (80, img.shape[0] - 250), cv.FONT_HERSHEY_SIMPLEX, 0.8,
               (0, 0, 0), 1)
    #=================================/UI
    cv.imshow('img_copy', img_masked)
    print("============Step 1 End============")
    cv.waitKey()
    return counter_number

#input>


for m in range(65,66):#对某些点进行测试# 28上一次测试的
    x_sample = dict_[m][0]
    y_sample = dict_[m][1]
    angle_temp_list = angle_round(x_sample, y_sample, 65)  # 第三个参数为圆的半径

    for i in range(1,73):
        x1=angle_temp_list[i-1][0]
        y1 = angle_temp_list[i - 1][1]
        cx=x_sample
        cy=y_sample
        temp_list=pixel_between_two_points(cx,round(x1),cy,round(y1))

        ray_lenth = 0
        compare_distance_value=0
        compare_color_value=255
        color_hist=[]
        #单条射线的所有点,颜色深度的集合,找出前三名
        color_deep_rank={}
        for m in range(0,len(temp_list)):
            x_temp=temp_list[m][0]
            y_temp=temp_list[m][1]

            single_lenth=cell_wall_ray_lenth(cx,cy,x_temp,y_temp)

            color_deep_rank[y_temp, x_temp] = gauss[y_temp][x_temp]
Пример #6
0
def step4(cell_id):
    display = cv.imread(
        "G:\\2020summer\\Project\\Cell_classfication_1.0.0\\temp.bmp")

    img = cv.imread(
        "G:\\2020summer\\Project\\Cell_classfication_1.0.0\\temp_1.bmp")
    img_result = img.copy()
    # img=cv.cvtColor(img,cv.COLOR_BGR2BGRA)

    # -----preprocess-----
    gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    # cv.imshow("gray", gray)

    gauss = cv.GaussianBlur(gray, (5, 5), 5)

    img_shape = gauss.shape

    # read from local
    f = open("G:\\2020summer\\Project\\Cell_classfication_1.0.0\\dict.txt",
             'r')
    dict_ = eval(f.read())
    f.close()
    #print("read from local : ", dict_)
    # distance from single point to center
    distance_from_single_point_to_center_list = []

    for m in range(cell_id, cell_id + 1):  # 对某些点进行测试# 28上一次测试的
        # <input
        file1 = open('data_smooth_output.txt', 'r')
        fixed_data = [float(x.strip()) for x in file1]
        file1.close()

        # input>

        x_sample = dict_[m][0]
        y_sample = dict_[m][1]
        angle_temp_list = angle_round(x_sample, y_sample, 65)  # 第三个参数为圆的半径

        for i in range(1, 73):
            x1 = angle_temp_list[i - 1][0]
            y1 = angle_temp_list[i - 1][1]
            cx = x_sample
            cy = y_sample
            temp_list = pixel_between_two_points(cx, round(x1), cy, round(y1))

            ray_lenth = 0
            compare_distance_value = 0
            compare_color_value = 255
            color_hist = []
            # 单条射线的所有点,颜色深度的集合,找出前三名
            color_deep_rank = {}
            for m in range(0, len(temp_list)):
                x_temp = temp_list[m][0]
                y_temp = temp_list[m][1]

                single_lenth = cell_wall_ray_lenth(cx, cy, x_temp, y_temp)

                color_deep_rank[y_temp, x_temp] = gauss[y_temp][x_temp]

                sorted_color_deep_rank = sorted(color_deep_rank.items(),
                                                key=lambda kv: (kv[1], kv[0]),
                                                reverse=False)

                if gauss[y_temp][x_temp] <= compare_color_value:
                    compare_color_value = gauss[y_temp][x_temp]
                    compare_distance_valuevalue = single_lenth

                    x_final = x_temp
                    y_final = y_temp
                else:
                    pass
                # ==hist graph
                color_hist.append(gauss[y_temp][x_temp])

            #print("**************** test: compare_color_value: ", compare_color_value, "dic rank: ",sorted_color_deep_rank[0], sorted_color_deep_rank[1], sorted_color_deep_rank[2])
            # plt.plot(color_hist, color="black")
            # plt.show()
            cv.circle(display, (round(x_final), round(y_final)), 1,
                      (0, 0, 255), -1)
            # cv.circle(img, (round(sorted_color_deep_rank[1][0][1]), round(sorted_color_deep_rank[1][0][0])), 1, (0, 255, 255), -1)
            # cv.circle(img, (round(sorted_color_deep_rank[2][0][1]), round(sorted_color_deep_rank[2][0][0])), 1, (0, 255, 255), -1)
            fixed_data_list = un_angle_round(x_sample, y_sample, fixed_data)
            #print(fixed_data_list)
            cv.circle(display, (round(
                fixed_data_list[i - 1][0]), round(fixed_data_list[i - 1][1])),
                      1, (0, 255, 0), -1)
            #cv.circle(display, (round(x1), round(y1)), 1, (255, 0, 255), -1)  # 半径显示

            # distance test and upload
            distance_from_single_point_to_center_list.append(
                distance(x_final, y_final, cx, cy))

        standard_r = math.ceil(mean(fixed_data))
        standard_error = 0
        for i in range(0, 72):
            standard_error += abs(fixed_data[i] - standard_r)

        area_calculate_from_points(fixed_data_list)
        #holo_area_calculate_from_points(fixed_data_list,gray,200)

        plt.show()
        #mean of r
        cv.circle(display, (x_sample, y_sample), math.ceil(standard_r),
                  (0, 255, 255), 0)
        print("not circle degree is: ",
              format(((standard_error / 72) / standard_r), '.2%'))
        #=========nucleus=======
        file1 = open('area_of_nucleus.txt', 'r')
        dataset1 = [float(x.strip()) for x in file1]
        file1.close()
        print("The area of cell nucleus is: ", round(dataset1[cell_id - 1]))

    cv.putText(display, "Chromophobe Kidney Cancer Test", (80, 30),
               cv.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 1)
    cv.putText(display, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
               (80, 60), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1)
    cv.putText(
        display, "The area of this cell is:" +
        str(area_calculate_from_points(fixed_data_list)),
        (80, (img.shape[1] - 220)), cv.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 1)
    cv.putText(
        display, "not circle degree is: " +
        str(format(((standard_error / 72) / standard_r), '.2%')),
        (80, img.shape[1] - 200), cv.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 1)

    #cv.imshow("step4 output", display)
    cv.imwrite(
        "G:\\2020summer\\Project\\Cell_classfication_1.0.0\\output_single\\" +
        str(cell_id) + ".bmp", display)
    #cv.waitKey()
    output1_non_circle_degree = (standard_error / 72) / standard_r
    return (output1_non_circle_degree)
def step1(path_slides=''):
    cv.destroyAllWindows()
    plt.close()

    os_path = os.getcwd()
    cell_area_hist_list = []
    # print("============Step 1 Start============")
    # -----read-----

    # if read_type==0:
    #     file_path=filedialog.askopenfilename()
    #
    # #img=cv.imread("G:\\2020summer\\Project\\Chromophobe_dataset1\\4.jpg")
    # else:
    #     file_path=path2imgs
    file_path = path_slides

    threshold_value = 190
    # threshold_value=threshold_test(file_path)

    if not os.path.exists(os_path + '\\bin\\output'):
        os.makedirs(os_path + '\\bin\\output')
    if not os.path.exists(os_path + '\\bin\\output'):
        os.makedirs(os_path + '\\result')
    if not os.path.exists(os_path + '\\bin\\output'):
        os.mkdir(os_path + '\\output_single')
    if not os.path.exists(os_path + '\\bin\\output'):
        os.makedirs(os_path + '\\result_pdf')
    img = cv.imread(file_path)
    img_original = img
    # print("Img size: [Width :",img.shape[0],"]","[Height :",img.shape[1],"]")
    if img.shape[0] < 450 or img.shape[1] < 600:
        img = cv.copyMakeBorder(img,
                                80,
                                450,
                                360,
                                360,
                                cv.BORDER_CONSTANT,
                                value=[255, 255, 255])
    else:
        img = cv.copyMakeBorder(img,
                                80,
                                450,
                                60,
                                60,
                                cv.BORDER_CONSTANT,
                                value=[255, 255, 255])
    img_masked = img.copy()
    img_nucleus_white_img = img.copy()

    # -----preprocess-----
    gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    # cv.imshow("gray", gray)

    gauss = cv.GaussianBlur(gray, (5, 5), 5)
    # cv.imshow("gauss1",gauss)

    ret, thresh = cv.threshold(gauss, threshold_value, 255, 0)
    # cv.imwrite("bin\\figure3_left.jpg",thresh)
    # cv.imshow("thresh",thresh)

    erode = cv.erode(thresh, None, iterations=1)
    # cv.imshow("erode",erode)

    # -----remove outlines-----

    # cv.imshow("erode",erode)
    for i in range(0, img.shape[0]):
        for j in range(0, img.shape[1]):
            erode[0][j] = 255
    # -----find contours-----
    img, cnts, hierarchy = cv.findContours(erode.copy(), cv.RETR_LIST,
                                           cv.CHAIN_APPROX_NONE)

    def cnt_area(cnt):
        area = cv.contourArea(cnt)
        return area

    counter_number = 0
    location_cells_center = {}
    area_of_cells_nucleus = []
    Whole_pic_cell_area_ave_percent = []
    Whole_pic_cell_color_ave = []
    x1 = 1
    y1 = 1
    x2 = 1
    y2 = 1
    x_sample = 1
    y_sample = 1

    for i in tqdm(range(0, len(cnts)), desc='Cell Nucleus Detecting'):
        x, y, w, h = cv.boundingRect(cnts[i])
        if 250 <= cnt_area(
                cnts[i]) <= 0.1 * (img.shape[0] * img.shape[1]) and cnt_area(
                    cnts[i]) / (w * h) > 0.4:
            # print('if true checkpoint')
            cell_area_hist_list.append(cnt_area(cnts[i]))
            # print(cnts[i])
            # cell_area_hist_list.append(area_calculate_from_points(cnts[i]))
            counter_number += 1
            # print(cnts[i])
            # print("======")
            cv.drawContours(img_masked, cnts[i], -1, (0, 0, 255),
                            2)  # draw contours
            cv.drawContours(img_nucleus_white_img, [cnts[i]], -1,
                            (255, 255, 255), -1)  # masked white
            M = cv.moments(cnts[i])

            # 检索每个细胞的内部颜色
            x, y, w, h = cv.boundingRect(cnts[i])

            # cv.imshow('single_cell', newimage)

            cell_area_percent = 0

            for row in range(y, y + h):
                for col in range(x, x + w):
                    result = cv.pointPolygonTest(cnts[i], (col, row), False)
                    if result == -1:
                        cv.circle(gray, (col, row), 1, 255, -1)
                        cv.circle(img, (col, row), 1, (255, 255, 255), -1)
                        cell_area_percent += 1
            cv.rectangle(img, (x, y), (x + w, y + h), (153, 153, 0), 1)
            newimage_gray = gray[y:y + h, x:x + w]

            Single_Cell_Color_Distrution = []
            for row in range(h):
                for col in range(w):
                    if newimage_gray[row, col] != 255:
                        Single_Cell_Color_Distrution.append(newimage_gray[row,
                                                                          col])
            # print('Single_Cell_Color_Distrution: ' + str(Single_Cell_Color_Distrution))
            '''
            plt.hist(Single_Cell_Color_Distrution,bins=50)
            plt.title(str(counter_number))
            plt.show()
            '''
            # print("this cell area percent= ",str(cell_area_percent/(w*h)))
            np.set_printoptions(precision=3)
            Whole_pic_cell_area_ave_percent.append(cnt_area(cnts[i]) / (w * h))
            if len(Single_Cell_Color_Distrution) > 0:
                Whole_pic_cell_color_ave.append(
                    np.nanmean(Single_Cell_Color_Distrution))
            """#找出masked细胞内点的坐标 find coordinates of cells in masked image
            rect = cv.minAreaRect(cnts[i])
            cx, cy = rect[0]
            box = cv.boxPoints(rect)
            box = np.int0(box)
            cv.drawContours(img_masked, [box], 0, (0, 0, 255), 2)
            #cv.circle(img_masked, (np.int32(cx), np.int32(cy)), 2, (255, 0, 0), 2, 8, 0)

            box_gray_color=[]
            for by in range(box[2][1],box[0][1]+1):
                for bx in range(box[1][0],box[3][0]+1):
                    #print(bx,by)
                    #cv.circle(img_masked,(bx, by), 1, (255, 0, 0), 2, 8, 0)
                    box_gray_color.append(gray[bx,by])
            plt.hist(box_gray_color)

            plt.hist(box_gray_color,bins=50)
            plt.title(str(counter_number))
            plt.show()

            dist=cv.pointPolygonTest(cnts[i],(50,50),True)
            """
            try:
                cX = int(M["m10"] / M["m00"])
                cY = int(M["m01"] / M["m00"])
                cv.circle(img_masked, (cX, cY), 3, (255, 255, 255), -1)
                cv.putText(img_masked, str(counter_number), (cX - 20, cY - 20),
                           cv.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
                area_of_cells_nucleus.append(cnt_area(cnts[i]))
                location_cells_center[counter_number] = [cX, cY]
            except:
                pass
            # if counter_number==1:
            #     x1=cX
            #     y1=cY
            # if counter_number==2:
            #     x2=cX
            #     y2=cY
            # if counter_number==3:
            #     x_sample=cX
            #     y_sample=cY

            # cv.drawContours(img_masked, [cnts[i]], -1, (255, 255, 255), -1)#mask contours

    ave_cell_nucleus_color = np.nanmean(Whole_pic_cell_color_ave)
    # pdb.set_trace()
    # print("Whole pic cell nucleus rectango area list: ", Whole_pic_cell_area_ave_percent)
    # print("Whole pic average cell nucleus area percent_ave: ", np.nanmean(Whole_pic_cell_area_ave_percent))
    # print("Whole pic average cell nucleus color deep percent: ", Whole_pic_cell_color_ave)
    # print("Whole pic average cell nucleus color deep percent_ave: ", ave_cell_nucleus_color)

    cv.imwrite("bin\\cell_clean.bmp", img)
    # -----put Text-----
    print("total cells number : ", counter_number)

    cv.line(img_masked, (x1, y1), (x2, y2), (0, 0, 255), 2)

    list_of_two_points = pixel_between_two_points(x1, x2, y1, y2)

    # -----output information on the line
    height_of_two_points = []
    height_of_two_points_B = []
    height_of_two_points_G = []
    height_of_two_points_R = []

    for m in range(0, len(list_of_two_points)):
        height = img[list_of_two_points[m][1], list_of_two_points[m][0]]
        try:
            height_B = img[list_of_two_points[m][1],
                           list_of_two_points[m][0]][0]
            height_G = img[list_of_two_points[m][1],
                           list_of_two_points[m][0]][1]
            height_R = img[list_of_two_points[m][1],
                           list_of_two_points[m][0]][2]
            height_of_two_points_B.append(height_B)
            height_of_two_points_G.append(height_G)
            height_of_two_points_R.append(height_R)
        except:
            pass
        # print(height)
        height_of_two_points.append(height)
    img_sample = img.copy()
    cv.circle(img_sample, (x_sample, y_sample), 3, (0, 0, 255), -1)
    font = cv.FONT_HERSHEY_SIMPLEX
    cv.putText(img_sample, "Sample_Point", (x_sample - 20, y_sample - 20),
               font, 0.7, (255, 255, 255), 2)

    # save to local
    f = open("bin\\dict.txt", 'w')
    f.write(str(location_cells_center))
    f.close()

    # < list save
    file1 = open('bin\\area_of_nucleus.txt', 'w')
    for fp in area_of_cells_nucleus:
        file1.write(str(fp))
        file1.write('\n')
    file1.close()
    # list save >

    cv.imwrite("bin\\temp.bmp", img_masked)
    cv.imwrite("bin\\temp_1.bmp", img_nucleus_white_img)
    cv.imwrite("bin\\figure3_right.jpg", img_masked)
    # ================hist of cells area==================
    plt.hist(cell_area_hist_list)
    # plt.show()

    # =================================
    # -----
    # =================================UI/
    cv.putText(img_masked, "Overview", (80, 40), cv.FONT_HERSHEY_SIMPLEX, 1,
               (0, 0, 0), 2)
    image_size_text = "Image size: [Width :" + str(
        img_original.shape[0]) + "]" + "[Height :" + str(
            img_original.shape[1]) + "]"
    cv.putText(img_masked, image_size_text, (80, img.shape[0] - 400),
               cv.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 2)
    cv.putText(img_masked, "Total cells number: " + str(counter_number),
               (80, img.shape[0] - 350), cv.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0),
               2)
    Cells_density = ('%.2f' % (10000 * counter_number /
                               (img.shape[0] * img.shape[1])))
    # print("Cells density : ",Cells_density," / 100*100 pixels")
    cv.putText(img_masked,
               "Cells density : " + str(Cells_density) + " / 100*100 pixels",
               (80, img.shape[0] - 300), cv.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0),
               2)
    cv.putText(img_masked, "Close window to continue",
               (80, img.shape[0] - 250), cv.FONT_HERSHEY_SIMPLEX, 0.8,
               (0, 0, 0), 1)
    # =================================/UI
    # cv.imshow("result", img_masked)
    # cv.imshow("img_sample_location_RED_DOT", img_sample)
    cv.imwrite("bin\\overview_result1.bmp", img_masked)
    # print("============Step 1 End============")
    # cv.waitKey()
    return counter_number, Cells_density, ave_cell_nucleus_color
def step1():

    print("============Step 1 Start============")
    #-----read-----
    img = cv.imread("G:\\2020summer\\Project\\Chromophobe_dataset1\\4.jpg")
    img = cv.copyMakeBorder(img,
                            80,
                            300,
                            80,
                            80,
                            cv.BORDER_CONSTANT,
                            value=[255, 255, 255])
    #img=cv.cvtColor(img,cv.COLOR_BGR2BGRA)

    img_masked = img.copy()
    img_nucleus_white_img = img.copy()

    #-----preprocess-----
    gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    #cv.imshow("gray", gray)

    gauss = cv.GaussianBlur(gray, (5, 5), 5)
    #cv.imshow("gauss1",gauss)

    ret, thresh = cv.threshold(gauss, 190, 255, 0)
    #cv.imshow("thresh",thresh)

    erode = cv.erode(thresh, None, iterations=2)
    #cv.imshow("erode",erode)
    #-----remove outlines-----

    cv.imshow("erode", erode)
    for i in range(0, img.shape[0]):
        for j in range(0, img.shape[1]):
            erode[0][j] = 255
    #-----find contours-----
    cnts, hierarchy = cv.findContours(erode.copy(), cv.RETR_LIST,
                                      cv.CHAIN_APPROX_NONE)

    def cnt_area(cnt):
        area = cv.contourArea(cnt)
        return area

    counter_number = 0
    location_cells_center = {}
    area_of_cells_nucleus = []
    for i in range(0, len(cnts)):
        if 250 <= cnt_area(cnts[i]) <= 0.8 * (img.shape[0] * img.shape[1]):
            counter_number += 1
            #print(cnts[i])
            #print("======")
            cv.drawContours(img_masked, cnts[i], -1, (0, 0, 255),
                            2)  #draw contours
            cv.drawContours(img_nucleus_white_img, [cnts[i]], -1,
                            (255, 255, 255), -1)  #masked white
            M = cv.moments(cnts[i])
            try:
                cX = int(M["m10"] / M["m00"])
                cY = int(M["m01"] / M["m00"])
                cv.circle(img_masked, (cX, cY), 3, (255, 255, 255), -1)
                cv.putText(img_masked, str(counter_number), (cX - 20, cY - 20),
                           cv.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
                area_of_cells_nucleus.append(cnt_area(cnts[i]))
                location_cells_center[counter_number] = [cX, cY]
            except:
                pass
            if counter_number == 6:
                x1 = cX
                y1 = cY
            if counter_number == 7:
                x2 = cX
                y2 = cY
            if counter_number == 1:
                x_sample = cX
                y_sample = cY
            #cv.drawContours(img_masked, [cnts[i]], -1, (255, 255, 255), -1)#mask contours
    #-----put Text-----
    print("total cells number : ", counter_number)

    #cv.line(img_masked, (x1,y1), (x2,y2), (0,0,255), 2)

    list_of_two_points = pixel_between_two_points(x1, x2, y1, y2)
    print(list_of_two_points)

    #-----output information on the line
    height_of_two_points = []
    height_of_two_points_B = []
    height_of_two_points_G = []
    height_of_two_points_R = []

    for m in range(0, len(list_of_two_points)):
        height = img[list_of_two_points[m][1], list_of_two_points[m][0]]
        try:
            height_B = img[list_of_two_points[m][1],
                           list_of_two_points[m][0]][0]
            height_G = img[list_of_two_points[m][1],
                           list_of_two_points[m][0]][1]
            height_R = img[list_of_two_points[m][1],
                           list_of_two_points[m][0]][2]
            height_of_two_points_B.append(height_B)
            height_of_two_points_G.append(height_G)
            height_of_two_points_R.append(height_R)
        except:
            pass
        #print(height)
        height_of_two_points.append(height)
    plt.plot(height_of_two_points, color="black")

    plt.show()
    try:
        plt.plot(height_of_two_points_B, color="blue")
        plt.plot(height_of_two_points_G, color="green")
        plt.plot(height_of_two_points_R, color="red")
        plt.savefig(
            "G:\\2020summer\\Project\\Cell_classfication_1.0.0\\Step1_output_2.jpg"
        )
        plt.show()
    except:
        pass

    img_sample = img.copy()
    cv.circle(img_sample, (x_sample, y_sample), 3, (0, 0, 255), -1)
    font = cv.FONT_HERSHEY_SIMPLEX
    cv.putText(img_sample, "Sample_Point", (x_sample - 20, y_sample - 20),
               font, 0.7, (255, 255, 255), 2)
    #cv.imshow("img_sample_location_RED_DOT", img_sample)
    print("x_sample = : ", x_sample)  #样本标注点的坐标
    print("y_sample = : ", y_sample)

    # save to local
    f = open("G:\\2020summer\\Project\\Cell_classfication_1.0.0\\dict.txt",
             'w')
    f.write(str(location_cells_center))
    f.close()
    print("save dict successfully.")

    # < list save
    file1 = open('area_of_nucleus.txt', 'w')
    for fp in area_of_cells_nucleus:
        file1.write(str(fp))
        file1.write('\n')
    file1.close()
    # list save >

    #-----
    cv.imshow('img_copy', img_masked)

    cv.imwrite("G:\\2020summer\\Project\\Cell_classfication_1.0.0\\temp.bmp",
               img_masked)
    cv.imwrite("G:\\2020summer\\Project\\Cell_classfication_1.0.0\\temp_1.bmp",
               img_nucleus_white_img)

    #==================================

    print("============Step 1 End============")
    cv.waitKey()
Пример #9
0
def step1(findpeaks=None):
    cell_area_hist_list = []
    print("============Step 1 Start============")
    #-----read-----
    root = tk.Tk()
    root.withdraw()

    file_path = filedialog.askopenfilename()
    #img=cv.imread("G:\\2020summer\\Project\\Chromophobe_dataset1\\4.jpg")
    img = cv.imread(file_path)
    print("Img size: [Width :", img.shape[0], "]", "[Height :", img.shape[1],
          "]")

    img = cv.copyMakeBorder(img,
                            80,
                            450,
                            60,
                            60,
                            cv.BORDER_CONSTANT,
                            value=[255, 255, 255])
    #img=cv.cvtColor(img,cv.COLOR_BGR2BGRA)

    img_masked = img.copy()
    img_nucleus_white_img = img.copy()

    #-----preprocess-----
    gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    #cv.imshow("gray", gray)

    gauss = cv.GaussianBlur(gray, (5, 5), 5)
    #cv.imshow("gauss1",gauss)

    ret, thresh = cv.threshold(gauss, 140, 255, 0)  #正常图数值140,癌症图190
    cv.imwrite(
        "G:\\2020summer\\Project\\Chromophobe_dataset1\\figure3_left.jpg",
        thresh)
    #cv.imshow("thresh",thresh)

    erode = cv.erode(thresh, None, iterations=2)
    #cv.imshow("erode",erode)

    #-----remove outlines-----

    #cv.imshow("erode",erode)
    for i in range(0, img.shape[0]):
        for j in range(0, img.shape[1]):
            erode[0][j] = 255
    #-----find contours-----
    cnts, hierarchy = cv.findContours(erode.copy(), cv.RETR_LIST,
                                      cv.CHAIN_APPROX_NONE)

    def cnt_area(cnt):
        area = cv.contourArea(cnt)
        return area

    counter_number = 0
    location_cells_center = {}
    area_of_cells_nucleus = []
    for i in range(0, len(cnts)):
        if 250 <= cnt_area(cnts[i]) <= 0.2 * (img.shape[0] * img.shape[1]):
            cell_area_hist_list.append(cnt_area(cnts[i]))
            #print(cnts[i])
            #cell_area_hist_list.append(area_calculate_from_points(cnts[i]))
            counter_number += 1
            #print(cnts[i])
            #print("======")
            cv.drawContours(img_masked, cnts[i], -1, (0, 0, 255),
                            2)  #draw contours
            cv.drawContours(img_nucleus_white_img, [cnts[i]], -1,
                            (255, 255, 255), -1)  #masked white
            M = cv.moments(cnts[i])

            #找出masked细胞内点的坐标
            '''            
            rect = cv.minAreaRect(cnts[i])
            cx, cy = rect[0]
            box = cv.boxPoints(rect)
            box = np.int0(box)
            #cv.drawContours(img_masked, [box], 0, (0, 0, 255), 2)
            #cv.circle(img_masked, (np.int32(cx), np.int32(cy)), 2, (255, 0, 0), 2, 8, 0)

            box_gray_color=[]
            for by in range(box[2][1],box[0][1]+1):
                for bx in range(box[1][0],box[3][0]+1):
                    #print(bx,by)
                    #cv.circle(img_masked,(bx, by), 1, (255, 0, 0), 2, 8, 0)
                    box_gray_color.append(gray[bx,by])
            #plt.hist(box_gray_color)

            plt.hist(box_gray_color,bins=50)
            plt.title(str(counter_number))
            #plt.show()

            dist=cv.pointPolygonTest(cnts[i],(50,50),True)

            '''

            try:
                cX = int(M["m10"] / M["m00"])
                cY = int(M["m01"] / M["m00"])
                cv.circle(img_masked, (cX, cY), 3, (255, 255, 255), -1)
                cv.putText(img_masked, str(counter_number), (cX - 20, cY - 20),
                           cv.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
                area_of_cells_nucleus.append(cnt_area(cnts[i]))
                location_cells_center[counter_number] = [cX, cY]
            except:
                pass
            if counter_number == 176:
                x1 = cX
                y1 = cY
            if counter_number == 181:
                x2 = cX
                y2 = cY
            if counter_number == 1:
                x_sample = cX
                y_sample = cY
            #cv.drawContours(img_masked, [cnts[i]], -1, (255, 255, 255), -1)#mask contours

    #-----put Text-----
    print("total cells number : ", counter_number)

    cv.line(img_masked, (x1, y1), (x2, y2), (0, 0, 255), 2)

    list_of_two_points = pixel_between_two_points(x1, x2, y1, y2)
    print(list_of_two_points)

    #-----output information on the line
    height_of_two_points_Gray = []
    height_of_two_points_B = []
    height_of_two_points_G = []
    height_of_two_points_R = []

    for m in range(0, len(list_of_two_points)):
        height_Gray = gray[list_of_two_points[m][1], list_of_two_points[m][0]]
        try:
            height_B = img[list_of_two_points[m][1],
                           list_of_two_points[m][0]][0]
            height_G = img[list_of_two_points[m][1],
                           list_of_two_points[m][0]][1]
            height_R = img[list_of_two_points[m][1],
                           list_of_two_points[m][0]][2]
            height_of_two_points_B.append(height_B)
            height_of_two_points_G.append(height_G)
            height_of_two_points_R.append(height_R)
        except:
            pass
        #print(height)
        height_of_two_points_Gray.append(height_Gray)
    #plt.plot(height_of_two_points_Gray,color="black")

    #plt.show()
    try:
        plt.title("RGB color between")
        plt.plot(height_of_two_points_B, color="blue")
        plt.plot(height_of_two_points_G, color="green")
        plt.plot(height_of_two_points_R, color="red")
        plt.tick_params(labelsize=13)
        plt.savefig(
            "G:\\2020summer\\Project\\Cell_classfication_1.0.0\\Step1_output_2.jpg"
        )
        plt.show()
        plt.title("gray color between")
        plt.tick_params(labelsize=13)
        plt.plot(height_of_two_points_Gray, color="black")
        plt.show()
    except:
        pass

    import scipy.signal
    #R##################
    plt.title("RGB color between")
    plt.plot(height_of_two_points_B, color="blue")
    plt.plot(height_of_two_points_G, color="green")
    plt.plot(height_of_two_points_R, color="red")

    print('Detect peaks without any filters.')

    height_of_two_points_Gray_reverse = [
        255 - i for i in height_of_two_points_R
    ]

    print('Detect peaks with minimum height and distance filters.')
    indexes, _ = scipy.signal.find_peaks(height_of_two_points_Gray_reverse,
                                         height=7,
                                         distance=2.1)
    print('Peaks are: %s' % (indexes))
    #clean
    indexes_1 = list(indexes)
    indexes_2 = []
    for i in indexes_1:
        if i < 0.25 * len(height_of_two_points_Gray_reverse) or i > 0.75 * len(
                height_of_two_points_Gray_reverse):

            indexes_2.append(i)
            indexes_1.remove(i)
            print(i, " is removed")

    print('Peaks fixed are: %s' % (indexes_1))
    if len(indexes_1) != 0:
        temp_list = [
            abs(i - (len(height_of_two_points_Gray) / 2)) for i in indexes_1
        ]

        indexes_1 = [indexes_1[temp_list.index(min(temp_list))]]

        #plt.title("gray color between_reverse_marked")
        #plt.plot(height_of_two_points_Gray, color="black")
        plt.plot(indexes_1, [height_of_two_points_R[i] for i in indexes_1],
                 marker="8",
                 markersize=10,
                 color='red',
                 ls="")
        #plt.plot(indexes_2, [height_of_two_points_Gray[i] for i in indexes_2], marker="8", markersize=10, color='green',ls="")

    else:
        print("Warning! Cell boundary detection failed!")

    # G##################
    print('Detect peaks without any filters.')

    height_of_two_points_Gray_reverse = [
        255 - i for i in height_of_two_points_G
    ]

    print('Detect peaks with minimum height and distance filters.')
    indexes, _ = scipy.signal.find_peaks(height_of_two_points_Gray_reverse,
                                         height=7,
                                         distance=2.1)
    print('Peaks are: %s' % (indexes))
    # clean
    indexes_1 = list(indexes)
    indexes_2 = []
    for i in indexes_1:
        if i < 0.25 * len(height_of_two_points_Gray_reverse) or i > 0.75 * len(
                height_of_two_points_Gray_reverse):
            indexes_2.append(i)
            indexes_1.remove(i)
            print(i, " is removed")

    print('Peaks fixed are: %s' % (indexes_1))
    if len(indexes_1) != 0:
        temp_list = [
            abs(i - (len(height_of_two_points_Gray) / 2)) for i in indexes_1
        ]

        indexes_1 = [indexes_1[temp_list.index(min(temp_list))]]

        #plt.title("gray color between_reverse_marked")
        #plt.plot(height_of_two_points_Gray, color="black")
        plt.plot(indexes_1, [height_of_two_points_G[i] for i in indexes_1],
                 marker="8",
                 markersize=10,
                 color='green',
                 ls="")

    else:
        print("Warning! Cell boundary detection failed!")

    # B##################
    print('Detect peaks without any filters.')

    height_of_two_points_Gray_reverse = [
        255 - i for i in height_of_two_points_B
    ]

    print('Detect peaks with minimum height and distance filters.')
    indexes, _ = scipy.signal.find_peaks(height_of_two_points_Gray_reverse,
                                         height=7,
                                         distance=2.1)
    print('Peaks are: %s' % (indexes))
    # clean
    indexes_1 = list(indexes)
    indexes_2 = []
    for i in indexes_1:
        if i < 0.25 * len(height_of_two_points_Gray_reverse) or i > 0.75 * len(
                height_of_two_points_Gray_reverse):
            indexes_2.append(i)
            indexes_1.remove(i)
            print(i, " is removed")

    print('Peaks fixed are: %s' % (indexes_1))
    if len(indexes_1) != 0:
        temp_list = [
            abs(i - (len(height_of_two_points_Gray) / 2)) for i in indexes_1
        ]

        indexes_1 = [indexes_1[temp_list.index(min(temp_list))]]

        #plt.title("gray color between_reverse_marked")
        #plt.plot(height_of_two_points_Gray, color="black")
        plt.plot(indexes_1, [height_of_two_points_B[i] for i in indexes_1],
                 marker="8",
                 markersize=10,
                 color='blue',
                 ls="")

    else:
        print("Warning! Cell boundary detection failed!")

    plt.tick_params(labelsize=13)
    plt.show()

    cv.imshow('img_copy', img_masked)

    cv.waitKey()