Beispiel #1
0
def cut_oct_2d(img_file, image_size=None):
    if isinstance(img_file, str):
        size = os.path.getsize(img_file)
        if size < THRETHOLD_FILESIZE:
            return None

        img1 = cv2.imread(img_file)
    else:
        img1 = img_file

    # img1.shape:(885,512,3)  (height,width,3)

    height, width = img1.shape[:-1]

    if height > width:  #TOPCON
        array_sum = np.sum(img1, axis=(1, 2))  # shape (885)

        top_n = heapq.nlargest(1, range(len(array_sum)), array_sum.take)

        bottom = max(0, top_n[0] - (img1.shape[1] // 2))
        top = min(img1.shape[0], top_n[0] + (img1.shape[1] // 2))

        img_crop = img1[bottom:top, :, :]

        if img_crop.shape[0] < img_crop.shape[1]:  # width < height
            add_black_pixel = img_crop.shape[1] - img_crop.shape[0]
            img_height_0 = np.zeros((add_black_pixel, img_crop.shape[1], 3))

            img_crop = np.concatenate((img_height_0, img_crop), axis=0)
        elif img_crop.shape[0] > img_crop.shape[1]:
            add_black_pixel = img_crop.shape[0] - img_crop.shape[1]
            img_width_0 = np.zeros((img_crop.shape[0], 3), add_black_pixel)
            img_crop = np.concatenate((img_width_0, img_crop), axis=1)

        if image_size is not None:
            img_crop = cv2.resize(img_crop, (image_size, image_size))

        return img_crop

    else:  #Carl Zeiss Jena
        return image_to_square(img1, image_size)
Beispiel #2
0
def do_preprocess_rop(img_source,
                      crop_size,
                      img_file_dest=None,
                      add_black_pixel_ratio=0):
    if isinstance(img_source, str):
        try:
            img1 = cv2.imread(img_source)
        except:
            # Corrupt JPEG data1: 19 extraneous bytes before marker 0xc4
            raise Exception("image file not found:" + img_source)
    else:
        img1 = img_source

    if img1 is None:  #file not exists or other errors
        raise Exception("image file error:" + img_source)

    img1 = del_black_or_white(img1)

    # after delete black margin, image may be too small
    min_width_height = min(img1.shape[:2])
    if min_width_height < IMG_SMALL_THRETHOLD:
        return None

    from LIBS.ImgPreprocess.my_image_helper import image_to_square
    img2 = image_to_square(img1, image_size=crop_size)

    if add_black_pixel_ratio > 0:
        img2 = add_black_margin(img2,
                                add_black_pixel_ratio=add_black_pixel_ratio)
        img2 = cv2.resize(img2, (crop_size, crop_size))

    if img_file_dest is not None:
        os.makedirs(os.path.dirname(img_file_dest), exist_ok=True)
        cv2.imwrite(img_file_dest, img2)

    return img2
def crop_posterior(img_source, circle_center, circle_diameter, diameter_times=3,
                   crop_circle=True, image_size=None):
    if isinstance(img_source, str):
        img_source = cv2.imread(img_source)
    else:
        img_source = img_source

    img_source = img_source.astype(np.uint8)

    circle_posterior = int(circle_diameter * diameter_times)

    '''
    (height, width) = img_file_source.shape[:-1]
        
    if (circle_center[0] - circle_posterior) < 0:
        out_of_region_left = True
        # circle_center[0] += abs(circle_center[0] - circle_posterior)
    else:
        out_of_region_left = False

    if (circle_center[0] + circle_posterior) > width:
        out_of_region_right = True
        # circle_center[0] -= circle_center[0] + circle_posterior
    else:
        out_of_region_right = False

    if (circle_center[1] - circle_posterior) < 0:
        out_of_region_bottom = True
        # circle_center[1] += abs(circle_center[1] - circle_posterior)
    else:
        out_of_region_bottom = False

    if (circle_center[1] + circle_posterior) > height:
        out_of_region_top = True
        # circle_center[1] -= circle_center[1] + circle_posterior
    else:
        out_of_region_top = False
    '''

    add_border_padding = 200
    img_source = image_border_padding(img_source, padding_left=add_border_padding, padding_right=add_border_padding,
                    padding_top=add_border_padding, padding_bottom=add_border_padding)

    circle_center1 = (circle_center[0] + add_border_padding, circle_center[1] + add_border_padding)

    if crop_circle:
        image_circle = np.zeros(img_source.shape)
        cv2.circle(image_circle, circle_center1, circle_posterior, (255, 255, 255), -1)

        # cv2.imwrite('/tmp4/aa0.jpg', img_file_source)
        # cv2.imwrite('/tmp4/aa1.jpg', image_circle)

        image_circle = image_circle // 255
        img_source = np.multiply(image_circle, img_source)

        # cv2.imwrite('/tmp4/aa2.jpg', img_file_source)

    img_crop_optic_disc = img_source[circle_center1[1] - circle_posterior:circle_center1[1] + circle_posterior,
                          circle_center1[0] - circle_posterior:circle_center1[0] + circle_posterior, :]  # width, height, channel

    from LIBS.ImgPreprocess.my_image_helper import image_to_square
    img_crop_optic_disc = image_to_square(img_crop_optic_disc, image_size=image_size)

    return img_crop_optic_disc
def detect_optic_disc(img_file_source,
                      preprocess=False,
                      img_file_blood_seg=None):
    str_uuid = str(uuid.uuid1())
    os.makedirs(os.path.join(dir_tmp, str_uuid), exist_ok=True)

    if preprocess:
        img_file_preprocess = os.path.join(dir_tmp, str_uuid,
                                           'preproces384.jpg')

        # from LIBS.ImgPreprocess.my_preprocess_dir import preprocess_image
        # preprocess_image(img_file_source, img_file_preprocess,
        #      crop_size=384, is_rop=False, add_black_pixel_ratio=0.07)

        from LIBS.ImgPreprocess.my_rop import resize_rop_image
        img_preprocess = resize_rop_image(img_file_source,
                                          image_to_square=True,
                                          output_shape=(384, 384))
        cv2.imwrite(img_file_preprocess, img_preprocess)
    else:
        img_file_preprocess = img_file_source

    #mask rcnn (384,384,3)
    img_file_mask_tmp = os.path.join(dir_tmp, str_uuid, 'mask.jpg')
    (confidence, img_file_mask, circle_center, circle_diameter) = \
        seg_optic_disc(model, img_file_preprocess,
            img_file_mask_tmp, image_shape=image_shape, return_optic_disc_postition=True)

    if confidence is not None:
        img_file_draw_circle = os.path.join(dir_tmp, str_uuid,
                                            'draw_circle.jpg')
        img_file_crop_optic_disc = os.path.join(dir_tmp, str_uuid,
                                                'crop_optic_dsc.jpg')

        img_draw_circle = optic_disc_draw_circle(img_file_preprocess,
                                                 circle_center,
                                                 circle_diameter,
                                                 diameter_times=3)
        cv2.imwrite(img_file_draw_circle, img_draw_circle)

        img_crop_optic_disc = crop_posterior(
            img_file_preprocess,
            circle_center,
            circle_diameter,
            diameter_times=my_config.posterior_diameter_times,
            image_size=299,
            crop_circle=False)
        cv2.imwrite(img_file_crop_optic_disc, img_crop_optic_disc)

        if img_file_blood_seg is None:
            return float(confidence[0]), img_file_mask_tmp, img_file_crop_optic_disc,\
                   img_file_draw_circle
        else:
            img_file_blood_vessel_seg_posterior = os.path.join(
                dir_tmp, str_uuid, 'blood_vessel_seg_posterior.jpg')
            from LIBS.ImgPreprocess.my_image_helper import image_to_square

            img_tmp1 = image_to_square(img_file_blood_seg, image_size=384)
            img_blood_vessel_seg_posterior = crop_posterior(
                img_tmp1,
                circle_center,
                circle_diameter,
                diameter_times=my_config.posterior_diameter_times,
                image_size=299,
                crop_circle=False)
            cv2.imwrite(img_file_blood_vessel_seg_posterior,
                        img_blood_vessel_seg_posterior)

            return float(confidence[0]), img_file_mask_tmp, img_file_crop_optic_disc, \
                   img_file_draw_circle, img_file_blood_vessel_seg_posterior

    else:
        if img_file_blood_seg is None:
            # return None, None, None, None #TypeError: cannot marshal None unless allow_none is enabled
            return -1, -1, -1, -1
        else:
            # return None, None, None, None, None
            return -1, -1, -1, -1, -1
for dir_path, subpaths, files in os.walk(dir_preprocess, False):
    for f in files:
        image_file = os.path.join(dir_path, f)

        (filepath, tempfilename) = os.path.split(image_file)
        (filename, extension) = os.path.splitext(tempfilename)
        if filename.endswith('_mask'):
            continue
        if not extension.upper() in [
                '.BMP', '.PNG', '.JPEG', '.JPG', '.TIFF', '.TIF'
        ]:
            continue

        if IMAGE_TO_SQUARE:
            img_input = image_to_square(image_file)
        else:
            img_input = image_file

        from LIBS.ImgPreprocess.my_patches_based_seg import seg_blood_vessel

        img_result = seg_blood_vessel(img_input,
                                      dicts_models,
                                      PATCH_H,
                                      PATCH_W,
                                      rop_resized=True,
                                      threshold=127,
                                      min_size=10,
                                      tmp_dir='/tmp',
                                      test_time_image_aug=True)
                        img_file_preprocess384,
                        circle_center,
                        circle_diameter,
                        diameter_times=3,
                        image_size=299,
                        crop_circle=CROP_POSTERIOR_CIRCLE)
                    img_file_crop_optic_disc = img_file_preprocess384.replace(
                        dir_preprocess384, dir_crop_optic_disc)
                    if not os.path.exists(
                            os.path.dirname(img_file_crop_optic_disc)):
                        os.makedirs(os.path.dirname(img_file_crop_optic_disc))
                    cv2.imwrite(img_file_crop_optic_disc, img_crop_optic_disc)

                if DO_BLOOD_VESSEL_SEG_POSTERIOR:
                    img_blood_vessel_seg = image_to_square(
                        img_file_preprocess384.replace(dir_preprocess384,
                                                       dir_blood_vessel_seg))
                    img_blood_vessel_seg = cv2.resize(img_blood_vessel_seg,
                                                      (384, 384))
                    img_blood_vessel_seg_posterior = crop_posterior(
                        img_blood_vessel_seg,
                        circle_center,
                        circle_diameter,
                        diameter_times=3,
                        image_size=299,
                        crop_circle=CROP_POSTERIOR_CIRCLE)

                    img_file_blood_vessel_seg_posterior = img_file_preprocess384.replace(
                        dir_preprocess384, dir_blood_vessel_seg_posterior)
                    if not os.path.exists(
                            os.path.dirname(
                                                   row[0] + '.jpg')
            if 'Testing' in file_type:
                image_file_original = os.path.join(dir_original, 'TestingSet',
                                                   row[0] + '.jpg')
            x, y = row[1], row[2]

            image_original = cv2.imread(image_file_original)

            (height, width) = image_original.shape[:-1]
            (bottom, top, left, right) = get_position(image_file_original)
            img_preprocess = crop_image(image_original, bottom, top, left,
                                        right)
            x, y = x - left, y - bottom

            (height, width) = img_preprocess.shape[:-1]
            img_preprocess = image_to_square(img_preprocess,
                                             image_size=preprocess_image_size)
            if width > height:
                y += math.ceil((width - height) / 2)
            elif height > width:
                x += math.ceil((height - width) / 2)
            rescale_ratio = max(width, height) / preprocess_image_size
            x /= rescale_ratio
            y /= rescale_ratio

            image_file_preprocess = image_file_original.replace(
                dir_original, dir_preprocess)
            os.makedirs(os.path.dirname(image_file_preprocess), exist_ok=True)
            cv2.imwrite(image_file_preprocess, img_preprocess)
            csv_writer.writerow(
                [image_file_preprocess,
                 round(x, 2), round(y, 2)])
Beispiel #8
0
#         filename, file_extension = os.path.splitext(img_file_source)
#
#         if file_extension == '.gif':
#             img_file_dest = img_file_source.replace('.gif', '.png')
#
#             img1 = imageio.imread(img_file_source)
#             print(img_file_dest)
#             imageio.imwrite(img_file_dest, img1)

filename_csv = 'BloodVessel384.csv'
df = pd.read_csv(filename_csv)  # panda dataframe

count = len(df.index)
for i in range(count):
    img_file = df.at[i, 'images']
    img_mask = df.at[i, 'masks']

    if not 'HRF' in img_file:
        continue

    print(img_file)

    img1 = cv2.imread(img_file)
    img2 = image_to_square(img1)
    cv2.imwrite(img_file, img2)

    img3 = cv2.imread(img_mask)
    img4 = image_to_square(img3)
    cv2.imwrite(img_mask, img4)

print('OK')