def main():
    print('\n')
    print('##############################################')
    print('##############################################')
    print('####                                      ####')
    print('####         DOWNSAMPLE SINOGRAM          ####')
    print('####                                      ####')
    print('##############################################')
    print('##############################################')
    print('\n')

    ##  Get input arguments
    args = getArgs()

    ##  Read input sinogram
    pathin = args.pathin
    if pathin[len(pathin) - 1] != '/':
        pathin += '/'

    filename = args.sino
    sino = io.readImage(pathin + filename)
    nang, npix = sino.shape

    print('\nInput path:\n', pathin)
    print('\nInput sinogram:\n', filename)
    print('Sinogram size: ', nang, ' ang  X  ', npix, ' pixels')

    ##  Getting projection geometry
    angles = create_projection_angles(args, nang)

    ##  Downsample sinogram
    angles_down = None

    if args.nproj is not None:
        sino_down, angles_down = downsample_sinogram_angles(sino, angles, args)

    elif args.factor is not None:
        sino_down = downsample_sinogram_pixels(sino, args)

    ##  Display check plot
    if args.plot is True:
        sino_list = [sino, sino_down]
        title_list = ['Original sinogram', 'Undersampled sinogram']
        dis.plot_multi(sino_list, title_list)

    ##  Write image & angle list
    write_output_files(sino_down, angles_down, args, pathin, filename)

    print('\n')
def main():
    print('\n')
    print('#######################################')
    print('#######################################')
    print('###                                 ###')
    print('###         MEAN SQUARE ERROR       ###')
    print('###                                 ###')
    print('#######################################')
    print('#######################################')
    print('\n')

    ##  Get input arguments
    args = getArgs()

    ##  Get oracle image
    currDir = os.getcwd()
    image1 = io.readImage(args.image1)
    image1 = image1.astype(myfloat)

    print('\nReading reference image:\n', args.image1)
    print('Image shape: ', image1.shape)

    image_list = []
    results = []

    ##  CASE OF SINGLE IMAGE TO ANALYZE
    if args.image2 is not None:
        if args.image2.find(':') == -1:
            image_list.append(args.image2)
            image2 = io.readImage(args.image2)
            image2 = image2.astype(myfloat)
            num_img = 1

            print('\nReading image to analyze:\n', args.image2)
            print('Image shape: ', image2.shape)

            ##  Get time in which the prgram starts to run
            time1 = time.time()

            ##  Scale image to analyze with respect to the reference one
            if args.scaling is True:
                print('\nPerforming linear regression ....')
                image2 = proc.linear_regression(image1, image2)

            ##  Register images
            if args.register is True:
                print('\nPerforming registration of the image to analize ....')
                image2 = proc.image_registration(image2, image1, 'ssd')

            ##  Crop resolution circle of the images
            if args.resol_circle is True:
                print('\nSelecting the resolution circle')
                image1 = proc.select_resol_square(image1)
                image2 = proc.select_resol_square(image2)

            ##  Crop images if enabled
            if args.roi is not None:
                roi = args.roi

                if args.roi.find(',') != -1:
                    roi = roi.split(',')
                    p0 = [int(roi[0].split(':')[1]), int(roi[0].split(':')[0])]
                    p1 = [int(roi[1].split(':')[1]), int(roi[1].split(':')[0])]

                    print('Cropping rectangular ROI with vertices:  ( ', \
                            p0[0],' , ', p0[1], ')   ( ', p1[0],' , ',p1[1], ')')

                    image1 = proc.crop_image(image1, p0, p1)
                    image2 = proc.crop_image(image2, p0, p1)

                else:
                    print('\nUsing pixels specified in file:\n', roi)
                    file_roi = open(roi, 'r')
                    pixels = np.loadtxt(file_roi)
                    image1 = image1[pixels[:, 0], pixels[:, 1]]
                    image2 = image2[pixels[:, 0], pixels[:, 1]]
                    num_pix = len(image1)
                    fact = factors(num_pix)
                    image1 = image1.reshape(fact[0], int(num_pix / fact[0]))
                    image2 = image2.reshape(fact[0], int(num_pix / fact[0]))

            ##  Compute the gradient of the images, if enabled
            if args.gradient is True:
                image1 = compute_gradient_image(image1)
                image2 = compute_gradient_image(image2)

            ##  Check whether the 2 images have the same shape
            if image1.shape != image2.shape:
                sys.error('\nERROR: The input images have different shapes!\n')

            ##  Plot to check whether the images have the same orientation
            if args.plot is True:
                print('\nPlotting images to check orientation ....')
                img_list = [image1, image2]
                title_list = ['Oracle image', 'Image to analyze']
                dis.plot_multi(img_list, title_list, 'Check plot')

            ##  Compute figures of merit
            SNR = calc_snr(image1, image2)
            PSNR = calc_psnr(image1, image2)
            RMSE = calc_rmse(image1, image2)
            MAE = calc_rmse(image1, image2)

            results.append(np.array([SNR, PSNR, RMSE, MAE]))

        ##  CASE OF MULTIPLE SPECIFIC IMAGES
        else:
            image_list = args.image2.split(':')
            img_list = []
            title_list = []
            num_img = len(image_list)

            for im in range(num_img):
                img_file = image_list[im]
                image1 = io.readImage(args.image1)
                image2 = io.readImage(img_file)  # image2 --> image to analyze
                image2 = image2.astype(myfloat)
                print('\nReading image to analyze:\n', args.image2)
                print('Image shape: ', image2.shape)

                ##  Get time in which the prgram starts to run
                time1 = time.time()

                ## Scale image to analyze with respect to the reference one
                if args.scaling is True:
                    print('\nPerforming linear regression ....')
                    image2 = proc.linearRegression(image1, image2)

                ## Register images
                if args.register is True:
                    print(
                        '\nPerforming registration of the image to analize ....'
                    )
                    image2 = proc.image_registration(image2, image1, 'ssd')

                ##  Crop resolution circle of the images
                if args.resol_circle is True:
                    print('\nSelecting the resolution circle')
                    image1 = proc.selectResolutionSquare(image1)
                    image2 = proc.selectResolutionSquare(image2)

                ##  Crop images if enabled
                if args.roi is not None:
                    roi = args.roi

                    if args.roi.find(',') != -1:
                        roi = roi.split(',')
                        p0 = [
                            int(roi[0].split(':')[1]),
                            int(roi[0].split(':')[0])
                        ]
                        p1 = [
                            int(roi[1].split(':')[1]),
                            int(roi[1].split(':')[0])
                        ]

                        print('Cropping rectangular ROI with vertices:  ( ', \
                                p0[0],' , ', p0[1], ')   ( ', p1[0],' , ',p1[1], ')')

                        image1 = proc.crop_image(image1, p0, p1)
                        image2 = proc.crop_image(image2, p0, p1)

                    else:
                        print('\nUsing pixels specified in file:\n', roi)
                        file_roi = open(roi, 'r')
                        pixels = np.loadtxt(file_roi)
                        pixels = pixels.astype(int)

                        image1 = image1[pixels[:, 0], pixels[:, 1]]
                        image2 = image2[pixels[:, 0], pixels[:, 1]]
                        num_pix = len(image1)
                        fact = factors(num_pix)
                        image1 = image1.reshape(fact[0],
                                                int(num_pix / fact[0]))
                        image2 = image2.reshape(fact[0],
                                                int(num_pix / fact[0]))

                ##  Compute the gradient of the images, if enabled
                if args.gradient is True:
                    image1 = compute_gradient_image(image1)
                    image2 = compute_gradient_image(image2)

                ##  Check whether the 2 images have the same shape
                if image1.shape != image2.shape:
                    sys.exit(
                        '\nERROR: The input images have different shapes!\n')

                ##  Plot to check whether the images have the same orientation
                if args.plot is True:
                    print('\nPlotting images to check orientation ....')
                    img_list2 = [image1, image2]
                    title_list2 = ['Oracle image', 'Image to analyze']
                    dis.plot_multi(img_list2, title_list2, 'Check plot')

                ##  Compute figures of merit
                SNR = calc_snr(image1, image2)
                PSNR = calc_psnr(image1, image2)
                RMSE = calc_rmse(image1, image2)
                MAE = calc_rmse(image1, image2)

                results.append(np.array([SNR, PSNR, RMSE, MAE]))

    ##  CASE OF BUNCH OF IMAGES TO ANALYZE
    else:
        os.chdir(args.path)
        image_list = sorted(glob.glob('*'))
        num_img = len(fileIn)

        ## Get time in which the prgram starts to run
        time1 = time.time()

        ## Loop on all the images to analyze
        for i in range(num_img):
            image1 = io.readImage(args.image1)
            image2 = io.readImage(image_list[i])
            image2 = image2.astype(myfloat)
            print('\n\n\nIMAGE TO ANALYZE NUMBER: ', i)
            print('\nReading image to analyze:\n', image_list[i])
            print('Image shape: ', image2.shape)

            if args.fileout is not None:
                fileout.write('\nReading image to analyze:\n' + fileIn[i])

            ## Scale image to analyze with respect to the reference one
            if args.scaling is True:
                print('\nPerforming linear regression ....')
                image2 = proc.linearRegression(image1, image2)

            ## Register images
            if args.register is True:
                print('\nPerforming registration of the image to analize ....')
                image2 = proc.image_registration(image2, image1, 'ssd')

            ##  Crop resolution circle of the images
            if args.resol_circle is True:
                print('\nSelecting the resolution circle')
                image1 = proc.selectResolutionSquare(image1)
                image2 = proc.selectResolutionSquare(image2)

            ##  Crop images if enabled
            if args.roi is not None:
                roi = args.roi

                if args.roi.find(',') != -1:
                    roi = roi.split(',')
                    p0 = [int(roi[0].split(':')[1]), int(roi[0].split(':')[0])]
                    p1 = [int(roi[1].split(':')[1]), int(roi[1].split(':')[0])]

                    print('Cropping rectangular ROI with vertices:  ( ', \
                            p0[0],' , ', p0[1], ')   ( ', p1[0],' , ',p1[1], ')')

                    image1 = proc.crop_image(image1, p0, p1)
                    image2 = proc.crop_image(image2, p0, p1)

                else:
                    print('\nUsing pixels specified in file:\n', roi)
                    file_roi = open(roi, 'r')
                    pixels = np.loadtxt(file_roi)
                    pixels = pixels.astype(int)

                    image1 = image1[pixels[:, 0], pixels[:, 1]]
                    image2 = image2[pixels[:, 0], pixels[:, 1]]
                    num_pix = len(image1)
                    fact = factors(num_pix)
                    image1 = image1.reshape(fact[0], int(num_pix / fact[0]))
                    image2 = image2.reshape(fact[0], int(num_pix / fact[0]))

                ##  Check whether the 2 images have the same shape
                if image1.shape != image2.shape:
                    sys.exit(
                        '\nERROR: The input images have different shapes!\n')

            ##  Compute the gradient of the images, if enabled
            if args.gradient is True:
                image1 = compute_gradient_image(image1)
                image2 = compute_gradient_image(image2)

            ##  Plot to check whether the images have the same orientation
            if args.plot is True and args.roi.find(',') != -1:
                print('\nPlotting images to check orientation ....')
                img_list2 = [image1, image2]
                title_list2 = ['Oracle image', 'Image to analyze']
                dis.plot_multi(img_list2, title_list2, 'Check plot')

            ##  Compute figures of merit
            SNR = calc_snr(image1, image2)
            PSNR = calc_psnr(image1, image2)
            RMSE = calc_rmse(image1, image2)
            MAE = calc_rmse(image1, image2)

            results.append(np.array([SNR, PSNR, RMSE, MAE]))

        os.chdir(currDir)

    ##  Summary print of the results
    print('\n\nSUMMARY OF THE RESULTS:\n')
    print('\nReference image:\n', args.image1)

    for i in range(num_img):
        print('\n\nTest image number ', i, '\n', image_list[i], '\n')
        print('SNR = ', results[i][0])
        print('PSNR = ', results[i][1])
        print('MRSE = ', results[i][2])
        print('MAE = ', results[i][3])

    ##  Get time elapsed for the run of the program
    time2 = time.time() - time1
    print('\n\nTime elapsed for the calculation: ', time2)

    ##  Write log file
    write_log_file(args, image_list, results)

    print('\n\n')
예제 #3
0
def main():
    print('\n')
    print('#######################################')
    print('#######################################')
    print('###                                 ###')
    print('###   STRUCTURAL SIMILARITY INDEX   ###')
    print('###                                 ###')
    print('#######################################')
    print('#######################################')
    print('\n')

    ##  Get input arguments
    args = getArgs()

    ## Get oracle image
    currDir = os.getcwd()
    image1 = io.readImage(args.image1)
    image1 = image1.astype(myfloat)

    print('\nReading reference image:\n', args.image1)
    print('Image shape: ', image1.shape)

    image_list = []
    results = []

    ##  CASE OF SINGLE IMAGE TO ANALYZE
    if args.image2 is not None:
        if args.image2.find(':') == -1:
            image_list.append(args.image2)
            image2 = io.readImage(args.image2)  # image2 --> image to analyze
            image2 = image2.astype(myfloat)
            num_img = 1

            print('\nReading image to analyze:\n', args.image2)
            print('Image shape: ', image2.shape)

            ## Get time in which the prgram starts to run
            time1 = time.time()

            ##  Scale image to analyze with respect to the reference one
            if args.scaling is True:
                print('\nPerforming linear regression ....')
                image2 = proc.linear_regression(image1, image2)

            ##  Register images
            if args.register is True:
                print('\nPerforming registration of the image to analize ....')
                image2 = proc.image_registration(image2, image1, 'ssd')

            ##  Crop resolution circle of the images
            if args.resol_circle is True:
                print('\nSelecting the resolution circle')
                image1 = proc.select_resol_square(image1)
                image2 = proc.select_resol_square(image2)

            ##  Crop images if enabled
            if args.roi is not None:
                roi = args.roi

                if roi.find(':') != -1:
                    roi = roi.split(',')
                    p0 = [int(roi[0].split(':')[1]), int(roi[0].split(':')[0])]
                    p1 = [int(roi[1].split(':')[1]), int(roi[1].split(':')[0])]

                    print('Cropping rectangular ROI with vertices:  ( ', \
                            p0[0],' , ', p0[1], ')   ( ', p1[0],' , ',p1[1], ')')

                    image1 = proc.crop_image(image1, p0, p1)
                    image2 = proc.crop_image(image2, p0, p1)

                else:
                    print('\nUsing pixels specified in file:\n', roi)
                    pixels = np.loadtxt(roi)
                    pixels = pixels.astype(int)
                    p0 = np.array([pixels[0, 0], pixels[0, 1]])
                    p1 = np.array([
                        pixels[len(pixels) - 1, 0], pixels[len(pixels) - 1, 1]
                    ])

                    print('Cropping rectangular ROI with vertices:  ( ', \
                            p0[0],' , ', p0[1], ')   ( ', p1[0],' , ',p1[1], ')')

                    image1 = proc.crop_image(image1, p0, p1)
                    image2 = proc.crop_image(image2, p0, p1)

            ##  Compute the gradient of the images, if enabled
            if args.gradient is True:
                image1 = compute_gradient_image(image1)
                image2 = compute_gradient_image(image2)

            ##  Check whether the 2 images have the same shape
            if image1.shape != image2.shape:
                sys.error('\nERROR: The input images have different shapes!\n')

            ##  Plot to check whether the images have the same orientation
            if args.plot is True:
                print('\nPlotting images to check orientation ....')
                img_list = [image1, image2]
                title_list = ['Oracle image', 'Image to analyze']
                dis.plot_multi(img_list, title_list, 'Check plot')

            ##  Get window size
            window_size = args.window
            print('\nSize of the computation window: ', window_size)

            if window_size % 2 != 0:
                window_size += 1
                print('Window size is even: window size changed to ',
                      window_size)

            ##  Get sigma of the gaussian kernel
            sigma = SIGMA
            print('Sigma of the gaussian kernel: ', sigma)

            ## Calculate map of SSIM values
            map_ssim, MSSIM = compute_map_ssim(image1, image2, window_size,
                                               sigma)
            results.append(MSSIM)

            if args.plot is True:
                print('\nPlotting images + map of ssim ....')
                img_list = [image1, image2, map_ssim]
                title_list = [
                    'Oracle image', 'Image to analyze', 'Map of SSIM'
                ]
                dis.plot_multi(img_list, title_list, 'Images and map of SSIM')

            ##  Save SSIM map
            filename = args.image2[:len(args.image2) - 4] + '_ssim_map.png'
            io.writeImage(filename, map_ssim)

        ##  CASE OF MULTIPLE SPECIFIC IMAGES
        else:
            image_list = args.image2.split(':')
            img_list = []
            title_list = []
            num_img = len(image_list)

            for im in range(num_img):
                img_file = image_list[im]
                image1 = io.readImage(args.image1)
                image2 = io.readImage(img_file)  # image2 --> image to analyze
                image2 = image2.astype(myfloat)
                print('\nReading image to analyze:\n', args.image2)
                print('Image shape: ', image2.shape)

                ##  Get time in which the prgram starts to run
                time1 = time.time()

                ##  Scale image to analyze with respect to the reference one
                if args.scaling is True:
                    print('\nPerforming linear regression ....')
                    image2 = proc.linearRegression(image1, image2)

                ##  Register images
                if args.register is True:
                    print(
                        '\nPerforming registration of the image to analize ....'
                    )
                    image2 = proc.image_registration(image2, image1, 'ssd')

                ##  Crop resolution circle of the images
                if args.resol_circle is True:
                    print('\nSelecting the resolution circle')
                    image1 = proc.selectResolutionSquare(image1)
                    image2 = proc.selectResolutionSquare(image2)

                ##  Crop images if enabled
                if args.roi is not None:
                    roi = args.roi

                    if args.roi.find(',') != -1:
                        roi = roi.split(',')
                        p0 = [
                            int(roi[0].split(':')[1]),
                            int(roi[0].split(':')[0])
                        ]
                        p1 = [
                            int(roi[1].split(':')[1]),
                            int(roi[1].split(':')[0])
                        ]

                        print('Cropping rectangular ROI with vertices:  ( ', \
                                p0[0],' , ', p0[1], ')   ( ', p1[0],' , ',p1[1], ')')

                        image1 = proc.crop_image(image1, p0, p1)
                        image2 = proc.crop_image(image2, p0, p1)

                    else:
                        print('\nUsing pixels specified in file:\n', roi)
                        pixels = np.loadtxt(roi)
                        pixels = pixels.astype(int)
                        p0 = np.array([pixels[0, 0], pixels[0, 1]])
                        p1 = np.array([
                            pixels[len(pixels) - 1, 0], pixels[len(pixels) - 1,
                                                               1]
                        ])

                        print('Cropping rectangular ROI with vertices:  ( ', \
                                p0[0],' , ', p0[1], ')   ( ', p1[0],' , ',p1[1], ')')

                        image1 = proc.crop_image(image1, p0, p1)
                        image2 = proc.crop_image(image2, p0, p1)

                ##  Compute the gradient of the images, if enabled
                if args.gradient is True:
                    image1 = compute_gradient_image(image1)
                    image2 = compute_gradient_image(image2)

                ##  Check whether the 2 images have the same shape
                if image1.shape != image2.shape:
                    sys.exit(
                        '\nERROR: The input images have different shapes!\n')

                ##  Plot to check whether the images have the same orientation
                if args.plot is True:
                    print('\nPlotting images to check orientation ....')
                    img_list2 = [image1, image2]
                    title_list2 = ['Oracle image', 'Image to analyze']
                    dis.plot_multi(img_list2, title_list2, 'Check plot')

                ##  Get window size
                window_size = args.window
                print('\nSize of the computation window: ', window_size)

                if window_size % 2 != 0:
                    window_size += 1
                    print('Window size is even: window size changed to ',
                          window_size)

                ##  Get sigma of the gaussian kernel
                sigma = SIGMA
                print('Sigma of the gaussian kernel: ', sigma)

                ##  Calculate map of SSIM values
                map_ssim, MSSIM = compute_map_ssim(image1, image2, window_size,
                                                   sigma)
                results.append(MSSIM)

                map_ssim[map_ssim < 0] = 0.0

                if args.plot is True:
                    img_list.append(map_ssim)
                    title_list.append('SSIM map n.' + str(im + 1))

                ##  Save SSIM map
                filename = img_file[:len(img_file) - 4] + '_ssim_map.png'
                io.writeImage(filename, map_ssim)

            if args.plot is True:
                print('\nPlotting images + map of ssim ....')
                dis.plot(img_list[0])
                dis.plot(img_list[1])
                dis.plot_multi_colorbar(img_list, title_list, 'Maps of SSIM')

    ##  CASE OF BUNCH OF IMAGES TO ANALYZE
    else:
        os.chdir(args.path)
        image_list = sorted(glob.glob('*'))
        num_images = len(image_list)
        img_list.append(image1)
        title_list.append('Oracle image')

        ##  Get time in which the prgram starts to run
        time1 = time.time()

        ##  Loop on all the images to analyze
        for i in range(num_img):
            image1 = io.readImage(args.image1)
            image2 = io.readImage(image_list[i])
            image2 = image2.astype(myfloat)

            print('\n\n\nIMAGE TO ANALYZE NUMBER: ', i)
            print('\nReading image to analyze:\n', fileIn[i])
            print('Image shape: ', image2.shape)

            ##  Scale image to analyze with respect to the reference one
            if args.scaling is True:
                print('\nPerforming linear regression ....')
                image2 = proc.linearRegression(image1, image2)

            ##  Register images
            if args.register is True:
                print('\nPerforming registration of the image to analize ....')
                image2 = proc.image_registration(image2, image1, 'ssd')

            ##  Crop resolution circle of the images
            if args.resol_circle is True:
                print('\nSelecting the resolution circle')
                image1 = proc.selectResolutionSquare(image1)
                image2 = proc.selectResolutionSquare(image2)

            ##  Crop images if enabled
            if args.roi is not None:
                roi = args.roi

                if args.roi.find(',') != -1:
                    roi = roi.split(',')
                    p0 = [int(roi[0].split(':')[1]), int(roi[0].split(':')[0])]
                    p1 = [int(roi[1].split(':')[1]), int(roi[1].split(':')[0])]

                    print('Cropping rectangular ROI with vertices:  ( ', \
                            p0[0],' , ', p0[1], ')   ( ', p1[0],' , ',p1[1], ')')

                    image1 = proc.crop_image(image1, p0, p1)
                    image2 = proc.crop_image(image2, p0, p1)

                else:
                    print('\nUsing pixels specified in file:\n', roi)
                    pixels = np.loadtxt(roi)
                    pixels = pixels.astype(int)
                    p0 = np.array([pixels[0, 0], pixels[0, 1]])
                    p1 = np.array([
                        pixels[len(pixels) - 1, 0], pixels[len(pixels) - 1, 1]
                    ])

                    print('Cropping rectangular ROI with vertices:  ( ', \
                            p0[0],' , ', p0[1], ')   ( ', p1[0],' , ',p1[1], ')')

                    image1 = proc.crop_image(image1, p0, p1)
                    image2 = proc.crop_image(image2, p0, p1)

            ##  Compute the gradient of the images, if enabled
            if args.gradient is True:
                image1 = compute_gradient_image(image1)
                image2 = compute_gradient_image(image2)

            ##  Check whether the 2 images have the same shape
            if image1.shape != image2.shape and args.roi is None:
                sys.error('\nERROR: The input images have different shapes!\n')

            ##  Plot to check whether the images have the same orientation
            if args.plot is True:
                print('\nPlotting images to check orientation ....')
                img_list = [image1, image2]
                title_list = ['Oracle image', 'Image to analyze']
                dis.plot_multi(img_list, title_list, 'Check plot')

            ##  Get window size
            window_size = args.window
            print('\nSize of the computation window: ', window_size)

            if window_size % 2 != 0:
                window_size += 1
                print('Window size is even: window size changed to ',
                      window_size)

            ##  Get sigma of the gaussian kernel
            sigma = SIGMA
            print('Sigma of the gaussian kernel: ', sigma)

            ##  Calculate map of SSIM values
            map_ssim, MSSIM = compute_map_ssim(image1, image2, window_size,
                                               sigma)
            results.append(MSSIM)

            ##  Diplay map of SSIM
            if args.plot is True:
                fig = plt.figure()
                plt.title('Map of SSIM indeces')
                plt.imshow(map_ssim, cmap=cm.Greys_r)
                #plt.colorbar()
                plt.show()

            ##  Save SSIM map
            filename = image_list[i][:len(image_list[i]) - 4] + '_ssim_map.png'
            io.writeImage(filename, map_ssim)
        os.chdir(currDir)

    ##  Summary print of the results
    print('\n\nSUMMARY OF THE RESULTS:\n')
    print('\nReference image:\n', args.image1)

    for i in range(num_img):
        print('\n\nTest image number ', i, '\n', image_list[i], '\n')
        print('SSIM = ', results[i])

    ##  Get time elapsed for the run of the program
    time2 = time.time() - time1
    print('\n\nTime elapsed for the calculation: ', time2)

    ##  Write log file
    write_log_file(args, image_list, results)

    print('\n\n')
def main():
    ##  Initial print
    print('\n')
    print('##########################################################')
    print('##########################################################')
    print('#####                                                #####')
    print('#####          ADMM Iterative Reconstruction         #####')
    print('#####                                                #####')
    print('##########################################################')
    print('##########################################################')
    print('\n')

    ##  Get input arguments
    args = getArgs()

    ##  Get input and output paths
    pathin, pathout = utils.get_io_path(args)

    print('\nInput path:\n', pathin)
    print('\nOutput path:\n', pathout)

    ##  Get input sinogram
    sino_list = []
    filein = []

    if args.filein is not None:
        sinoname = pathin + args.filein
        sino = io.readImage(sinoname).astype(myfloat)
        if args.angle_pi is True:
            sino = sino[:sino.shape[0] - 1, :]
        nang, npix = sino.shape
        nz = 1
        sino_list.append(sino)
        filein.append(args.filein)
        print('\nSinogram to reconstruct:\n', sinoname)

    else:
        print('\nReading stack of images\n')
        curr_dir = os.getcwd()
        os.chdir(pathin)

        for f in os.listdir('./'):
            if f.endswith('.DMP') is True:
                ext = '.DMP'
                break
            elif f.endswith('.tif') is True:
                ext = '.tif'
                break
            else:
                sys.exit('\nERROR: no .DMP or .tif file found in:\n' + pathin)

        filein.append(sorted(glob.glob('*' + ext)))
        nz = len(filein[0])
        os.chdir(curr_dir)

        print('Stack extension: ', ext)
        print('Number of slices: ', nz)

        print('\nLoading images .... ')
        for i in range(nz):
            if i == 0:
                sino = io.readImage(pathin + filein[0][i]).astype(myfloat)
                nang, npix = sino.shape
                sino_list.append(sino)
            else:
                sino_list.append(
                    io.readImage(pathin + filein[0][i]).astype(myfloat))
        print(' done! ')

    print('\nNumber of projection angles: ', nang)
    print('Number of pixels: ', npix)

    ##  Check plot
    if args.plot is True:
        if nz == 1:
            dis.plot(sino_list[0], 'Input sinogram')
        else:
            nzz = np.int(nz * 0.5)
            dis.plot(sino_list[nzz], 'Input sinogram')

    ##  Center of rotation axis
    if args.ctr == -1:
        ctr = npix * 0.5

    elif args.ctr != -1:
        ctr = args.ctr

    ##  Enable edge padding
    if args.lt is True:
        edf = 0.87
    elif args.lt is False and args.edge_padding != 0:
        edf = args.edge_padding
    else:
        edf = 0.0

    if edf:
        npix_old = npix
        for i in range(nz):
            sino_list[i] = proc.sino_edge_padding(sino_list[i], edf)
        npix = sino_list[0].shape[1]
        i1 = myint((npix - npix_old) * 0.5)
        i2 = i1 + npix_old
        ctr += i1

        print('\nEdge padding: ', edf)
        print('Number of edge-padded pixels: ', npix)
        print('Index start: ', i1, '   Index end: ', i2)
        print('Center of rotation axis new position: ', ctr)

        if args.plot is True:
            if nz == 1:
                dis.plot(sino_list[0], 'Sinogram with edge-padding')
            else:
                nzz = np.int(nz * 0.5)
                dis.plot(sino_list[nzz], 'Input sinogram')

    else:
        npix_old = npix
        i1 = 0
        i2 = npix

    ##  Compute differential sinogram if DBP option enabled
    if args.dbp is True:
        print('\nComputing differential sinogram ....')
        for i in range(nz):
            sino_list[i] = proc.diff_sino_savitzky_golay(sino_list[i],
                                                         window_size=args.sg)

        if args.plot is True:
            dis.plot(sino_list[0], 'Differential sinogram')

    ##  Correct for the center of rotation axis
    if args.ctr != -1:
        for i in range(nz):
            sino_list[i] = proc.sino_correct_rot_axis(sino_list[i], ctr)

    print('\nCenter of rotation axis position: ', ctr)
    print('Center of rotation corrected')

    ##  Get geometry
    if args.geometry == '0':
        angles = utils.create_projection_angles(nang)
    else:
        angles = utils.create_projection_angles(textfile=pathin +
                                                args.geometry)

    ##  Getting stopping criterion
    print('\nSetup of the iterative procedure:')

    if nz == 0:
        labelout = pathout + filein[0][:len(filein[0]) - 4]
    else:
        labelout = pathout + filein[0][0][:len(filein[0]) - 4]

    param = cap.admm_param(npix_old, nang, nz, ctr, labelout, args)

    print('Projectors enabled: ', args.projector)

    if args.dbp is True:
        print('DBP reconstruction enabled')

    if args.dpc is True:
        print('DPC reconstruction enabled')

    if args.n_iter is not None:
        print('Number of iterations: ', param.n_iter)

    if args.eps is not None:
        print('Stopping epsilon: ', param.eps)

    if args.n_iter_pcg is not None:
        print('Number of PCG iterations: ', param.n_iter_pcg)

    if args.plot is True:
        print('Interactive plot:', param.plot)

    if args.logfile is True:
        print('Interactive plot:', param.logfile)

    if param.reg is not None:
        if param.reg == 'cg':
            print('Conjugate gradient')
        if param.reg == 'lasso':
            print('Regularization type: Lasso L1')
        elif param.reg == 'lasso-tv':
            print('Regularization type: Lasso TV')
        elif param.reg == 'pp-breg':
            print('Regularization type: Plug and Play -- TV Bregman')
        elif param.reg == 'pp-chamb':
            print('Regularization type: Plug and Play -- TV Chambolle')
        elif param.reg == 'pp-nlmeans':
            print('Regularization type: Plug and Play -- Non Local Means')
        elif param.reg == 'pp-tgv':
            print(
                'Regularization type: Plug and Play -- Total generalized variation'
            )
        elif param.reg == 'pp-nltv':
            print(
                'Regularization type: Plug and Play -- Non-local total variation'
            )

        if param.reg != 'cg':
            print('\nLambda 1: ', param.lambd1)
            print('Lambda 2: ', param.lambd2)
            print('Mu:       ', param.mu)

    if args.init_object is True:
        print('\nInitialization with FBP reconstruction:', param.init_object)

    if param.mask is not None:
        print('\nObject support enabled')
        if param.plot is True:
            dis.plot(param.mask, 'Object support')

    if param.mask_add is not None:
        print('\nAdditional supports provided')
        if param.plot is True:
            if param.mask_add_n == 1:
                dis.plot(param.mask_add[0])
            else:
                dis.plot_multi(param.mask_add)

    if param.lt is True:
        print('\nLocal tomography mode enabled')

    ##  Iterative reconstruction
    print('\n\nReconstructing with ADMM ....')
    time1 = time.time()
    reco_list, info = admm(sino_list, angles, param)
    time2 = time.time()
    print('.... reconstruction done!')

    for i in range(nz):
        ##  Crop reconstruction if edge-padding enabled
        if edf != 0.0:
            reco = reco_list[i, i1:i2, i1:i2]
        else:
            reco = reco_list[i, :, :]

        ##  Show reconstruction
        if args.plot is True and nz == 1 and args.reg != 'cg':
            dis.plot(reco, 'Reconstruction')
            plot_convergence_curves(info)
        elif args.plot is True and i == nzz and args.reg != 'cg':
            nzz = np.int(nz * 0.5)
            dis.plot(reco_list[nzz, :, :],
                     'Reconstruction of slice ' + str(nzz))

        ##  Save reconstruction
        if nz == 1:
            save_reco(pathout, filein[0], args, param, reco)
        else:
            save_reco(pathout, filein[0][i], args, param, reco)

    ##  Time elapsed for the reconstruction
    time_tot = (time2 - time1) / 60.0
    print('\nTime elapsed for the reconstruction: ', time_tot)

    ##  Write log file
    if args.logfile is True:
        write_logfile(pathin, pathout, args, angles, ctr, param, time_tot,
                      info)

        write_info(pathout, filein[0], info, param, args)

    ##  Final print
    print('\n')
    print('\n')
    print('##########################################################')
    print('##########################################################')
    print('#####                                                #####')
    print('#####             ADMM Reconstruction done!          #####')
    print('#####                                                #####')
    print('##########################################################')
    print('##########################################################')
    print('\n')
예제 #5
0
def main():
    ##  Initial print
    print(
        '''\nThe program will execute in order 4 tests for the various implementation of the forward and backprojector'''
    )

    print(
        '''\nEvery time an image is displayed the code is temporarily halted. To the successive tests close the image'''
    )

    #############################################################
    ##  Test n.1
    #############################################################
    inp = raw_input('\n\nProceed with test n.1? (y/n) ')
    if inp == 'n':
        exit()

    print('###################################################')
    print('###                                             ###')
    print('###        TEST 1: Test adjoint operator        ###')
    print('###                                             ###')
    print('###################################################')

    print('\nTest adjoint for DISTANCE-DRIVEN:')
    test1('dd')
    print('\nTest adjoint for PIXEL-DRIVEN:')
    test1('pd')
    print('\nTest adjoint for RAY-DRIVEN:')
    test1('rd')
    print('\nTest adjoint for SLANT-STACKING:')
    test1('ss')
    print('\nTest adjoint for BSPLINE:')
    test1('bsp')

    #############################################################
    ##  Test n.2
    #############################################################
    inp = raw_input('\n\nProceed with test n.2? (y/n) ')
    if inp == 'n':
        exit()

    print('###################################################')
    print('###                                             ###')
    print('###        TEST 2: Test forward operator        ###')
    print('###                                             ###')
    print('###################################################')

    print('\nTest forward operator for DISTANCE-DRIVEN:')
    sino1 = test2('dd')
    print('\nTest forward operator for PIXEL-DRIVEN:')
    sino2 = test2('pd')
    print('\nTest forward operator for RAY-DRIVEN:')
    sino3 = test2('rd')
    print('\nTest forward operator for SLANT-STACKING:')
    sino4 = test2('ss')
    print('\nTest forward operator for BSPLINE:')
    sino5 = test2('bsp')

    dis.plot_multi(
        [sino1, sino2, sino3, sino4, sino5],
        ['DIST-DRIV', 'PIX-DRIV', 'RAY-DRIV', 'SLANT-STACK', 'BSPLINE'])

    #############################################################
    ##  Test n.3
    #############################################################
    inp = raw_input('\n\nProceed with test n.3? (y/n) ')
    if inp == 'n':
        exit()

    print('###################################################')
    print('###                                             ###')
    print('###          TEST 3: Test backprojector         ###')
    print('###                                             ###')
    print('###################################################')

    print('\nTest non-filtered backprojection for DISTANCE-DRIVEN:')
    reco1 = test3('dd', sino1)
    print('\nTest non-filtered backprojection for PIXEL-DRIVEN:')
    reco2 = test3('pd', sino2)
    print('\nTest non-filtered backprojection for RAY-DRIVEN:')
    reco3 = test3('rd', sino3)
    print('\nTest non-filtered backprojection for SLANT-STACKING:')
    reco4 = test3('ss', sino4)
    print('\nTest non-filtered backprojection for BSPLINE:')
    reco5 = test3('bsp', sino5)

    dis.plot_multi(
        [reco1, reco2, reco3, reco4, reco5],
        ['DIST-DRIV', 'PIX-DRIV', 'RAY-DRIV', 'SLANT-STACK', 'BSPLINE'])

    #############################################################
    ##  Test n.4
    #############################################################
    inp = raw_input('\n\nProceed with test n.4? (y/n) ')
    if inp == 'n':
        exit()

    print('###################################################')
    print('###                                             ###')
    print('###              TEST 4: Test FBP               ###')
    print('###                                             ###')
    print('###################################################')

    print('\nTest filtered backprojection for DISTANCE-DRIVEN:')
    reco1 = test4('dd', sino1)
    print('\nTest filtered backprojection for PIXEL-DRIVEN:')
    reco2 = test4('pd', sino2)
    print('\nTest filtered backprojection for RAY-DRIVEN:')
    reco3 = test4('rd', sino3)
    print('\nTest filtered backprojection for SLANT-STACKING:')
    reco4 = test4('ss', sino4)
    print('\nTest filtered backprojection for BSPLINE:')
    reco5 = test4('bsp', sino5)

    dis.plot_multi(
        [reco1, reco2, reco3, reco4, reco5],
        ['DIST-DRIV', 'PIX-DRIV', 'RAY-DRIV', 'SLANT-STACK', 'BSPLINE'])
예제 #6
0
def main():

    print('\n')
    print('#############################################################')
    print('############  FOURIER RING CORRELATION ANALYSIS  ############')
    print('#############################################################')
    print('\n')

    ##  Get input arguments
    args = getArgs()

    ##  Get output folder
    if args.pathout is not None:
        pathout = args.pathout
        if pathout[len(pathout) - 1] != '/':
            pathout += '/'
        if os.path.exists(pathout) is False:
            os.mkdir(pathout)
    else:
        pathout = None

    ##  Get number of pair of images
    image_string = args.images
    file_list = []

    if image_string.find(',') != -1:
        image_string = image_string.split(',')
        num_img_pair = len(image_string)

        for i in range(num_img_pair):
            file_list.append(image_string[i].split(':'))

    else:
        file_list.append(image_string.split(':'))
        num_img_pair = 1

    num_img = num_img_pair * 2

    print('Number of images to analyze: ', num_img)

    ##  Read input images and display them as check
    images = []
    prefix = []

    for i in range(num_img_pair):
        for j in range(2):
            ##  Read single image
            image_name = file_list[i][j]
            image = io.readImage(image_name)
            m, n = image.shape

            ##  Crop it as a square image
            npix = np.min((m, n))
            i1 = int(0.5 * (m - npix))
            i2 = int(0.5 * (n - npix))
            image = image[i1:i1 + npix, i2:i2 + npix]

            print('Reading image: ', image_name)

            ##  Select resolution square
            if args.resol_square is True:
                print('Calculation enabled in the resol square')
                image = proc.select_resol_square(image)

            ##  Apply hanning window
            if args.hanning is True:
                window = np.hanning(npix)
                window = np.outer(window, window)
                image *= window

            images.append(image)

        ##  Get common prefix
        prefix.append(common_string([file_list[i][0], file_list[i][1]]))

        ##  Check plot
        if args.plot is True:
            dis.plot_multi(
                [images[2 * i], images[2 * i + 1]],
                ['Input image ' + str(2 * i), 'Input image ' + str(2 * i + 1)])

    ##  Get labels for plots
    labels = None
    if args.labels is not (None):
        labels = args.labels
        labels = labels.split(':')

        if (2 * len(labels)) != num_img:
            sys.exit(
                '\nERROR: Number of labels is not half number of input images!\n'
            )

    ##  Fourier ring correlation analysis
    frc_curves = []

    for i in range(num_img_pair):
        print('\nCalculating FRC between:\n1)', file_list[i][0],'\n2)',\
                file_list[i][1])

        FRC, spatial_freq = analysis_frc(images[2 * i],
                                         images[2 * i + 1],
                                         args,
                                         pathout,
                                         prefix[i],
                                         file_list[i],
                                         labels=None)
        frc_curves.append(FRC)
    frc_curves = np.array(frc_curves).reshape(num_img_pair, len(spatial_freq))

    ##  Plot FRC curves
    if num_img_pair > 1:
        title = 'FRC - Comparison'
        prefix = 'comparison_curves'
        plot_frc_curves(frc_curves,
                        spatial_freq,
                        args,
                        pathout,
                        prefix,
                        title,
                        labels,
                        mode='multi')

    print('\n##########  FOURIER RING CORRELATION ANALYSIS END  ##########\n')