예제 #1
0
파일: combine.py 프로젝트: vterron/repipy
def compute_scales(input_images, scale_type, mask_key):
    """ From the list of images, use the central third of the image to
        calculate the scaling factor requested by user. """
    lx, ly = fits.getdata(input_images[0]).shape
    centre = [lx/3, ly/3, lx*2/3, ly*2/3]  # min_x, min_y, max_x, max_y
    scales = []
    for image in input_images:
        im = utils.read_image_with_mask(image, mask_keyword=mask_key, limits=centre)
        if scale_type == "median":
            new_item = numpy.ma.median(im)
        elif scale_type == "mean":
            new_item = numpy.ma.mean(im)
        elif scale_type == "none":
            new_item = 1
        if new_item is numpy.ma.masked:  # Result if all elements where masked
            new_item = 1
            print "All elements of the central part of image %s seem to be masked. "+\
                  "Replacing scale calculation by 1." % image
        scales.append(new_item)
    return scales  # cases where of all elements were masked
예제 #2
0
파일: combine.py 프로젝트: vterron/repipy
def cube_images(input_images, mask_key, scales, limits=0):
    """ From a set of images (input_images), and once divided by their scales, 
        form a cube with all the images. """
    # Set the limits to build the piece of the cube
    header = fits.getheader(input_images[0])
    if limits == 0:
        min_x, min_y = (0, 0)
        max_x, max_y = header["NAXIS2"], header["NAXIS1"]
    else:
        min_x, min_y, max_x, max_y = limits

    # Initialize the cube and the mask.
    lx, ly = max_x - min_x, max_y - min_y
    lz = len(input_images)
    mask = numpy.zeros([lz,lx,ly])  # initialized to zero, all pixels are valid
    cube = numpy.ma.array(mask, mask=mask) 

    # Now read all the images (and masks, if present), into the cube
    for index, image in enumerate(input_images):
        im = utils.read_image_with_mask(image, mask_keyword = mask_key, limits=[min_x, min_y, max_x, max_y])
        cube.data[index,:,:] = im.data/scales[index]
        cube.mask[index,:,:] = im.mask
    return cube    
예제 #3
0
def filter_image(args):
    """ Routine that uses a median filter on a list of masked images. """
    output_list = []
    for image in args.input:
        # Read image, mask and header
        im = utils.read_image_with_mask(image, mask_keyword=args.mask_key)
        hdr = fits.getheader(image)
        
        # skimage uses masks where 1 means valid and 0 invalid
        mask = (im.mask + 1) % 2
        filt_im = skimages.filter.median_filter(im.data, mask=mask, radius=args.radius)
        
        # Make name of file if not given
        if args.output == "":
            output = utils.add_suffix_prefix(image, suffix='-mf')
        else :
            output = args.output
        
        # Add history line to the header and write to file
        hdr.add_history("- Image median filtered. Radius = " + str(args.radius))
        fits.writeto(output, filt_im, header=hdr)
        output_list.append(output)
    return output_list
예제 #4
0
파일: arith.py 프로젝트: vterron/repipy
def arith(args):
    output_list = []        
    for image in args.input1:        
        # Read inputs as masked arrays or numbers (input2 might be a scalar)  
        im1 = utils.read_image_with_mask(image, args.mask_key)        
        try: # if second operand is a number we still need it in a masked array
            im2 = numpy.ma.array([float(args.input2[0])],mask=[0])
        except (ValueError,TypeError):
            im2 = utils.read_image_with_mask(args.input2[0], args.mask_key)        

        # Do the actual operation. Result is a masked array which masks 
        # any pixel if it is masked either in im1 or in im2.
        operations = {"+":operator.add, 
                      "-":operator.sub, 
                      "*":operator.mul,
                      "/":operator.div,
                      "**":operator.pow}

        # Case of mean or median for Input2 
        if args.median == True:
            operand2 = numpy.ma.median(im2)
        elif args.mean == True:
            operand2 = numpy.ma.mean(im2)
        else:
            operand2 = im2.data

        oper = operations[args.operation[0]]
        result = numpy.zeros_like(im1)
        result.data[:] = oper(im1.data, operand2)  # Actual operation of images                
        result.mask[:] = im1.mask | im2.mask       # If any is masked, result is       


        # If args.fill_val is present, use it
        if args.fill_val != '':
            result.data[:] = result.filled(float(args.fill_val))
                    
        # If output exists use it, otherwise use the input. Prefix/suffix might
        # modify things in next step.
        if args.output != '': 
            outpt = os.path.abspath(args.output)
        else:
            outpt = os.path.abspath(image)
            
        # Separate (path, file) and (file root, extensions). Then build new name. 
        outdir, outfile = os.path.split(outpt)   
        outfile_root, outfile_ext = re.match(r'(^.*?)(\..*)', outfile).groups()   
        outpt = os.path.join(outdir, args.prefix + outfile_root + args.suffix + 
                             outfile_ext)                         

        # Now name for the mask, if the name exists, use it, otherwise build it.
        if args.mask_name != "":
            mask_name = args.mask_name
        else:
            mask_name = outpt + ".msk"

        # Prepare a header starting from input1 header 
        hdr_im = fits.getheader(image)
        name2 = os.path.split(args.input2[0])[1]
        if args.median:  # if single number because median used
            name2 = "median(" + name2 + ") (" + str(im2) + ")"
        elif args.mean:  # if single number because mean used
            name2 = "mean(" + name2 + ") (" + str(im2) + ")"
            
        # Write a HISTORY element to the header    
        #hdr_im.add_history(" - Operation performed: " + image + " " + 
        #                   args.operation[0] + " " + name2)
        try:
            hdr_mask = fits.PrimaryHDU(result.mask.astype(int)).header
        except:
            print type(im1), type(result), type(im2)
            print im1
            print result
            print im2
           
        hdr_mask.add_history("- Mask corresponding to image: " + outpt)
        
        # Now save the resulting image and mask
        if os.path.isfile(outpt):
            os.remove(outpt)
        if os.path.isfile(mask_name):
            os.remove(mask_name)
        fits.writeto(outpt, result.data, header=hdr_im) 
        fits.writeto(mask_name, result.mask.astype(numpy.int0), header=hdr_mask)
        output_list.append(outpt)
    return output_list
예제 #5
0
def arith(args):
    output_list = []        
    for operand1, operand2 in zip(args.input1, args.input2):
        # Read inputs as masked arrays or numbers (input2 might be a scalar)  
        im1 = utils.read_image_with_mask(operand1, args.mask_key)
        try: # if second operand is a number we still need it in a masked array
            value2 = numpy.ma.array([float(operand2)],mask=[0])
        except (ValueError,TypeError):
            value2 = utils.read_image_with_mask(operand2, args.mask_key)

        # If --keyword was passed, read from the header of the image the value and use it, instead of the full image
        if args.keyword:
            value2 = numpy.ma.array( fits.getval(operand2, args.keyword) )

        # Do the actual operation. Result is a masked array which masks 
        # any pixel if it is masked either in im1 or in im2.
        operations = {"+":operator.add, 
                      "-":operator.sub, 
                      "*":operator.mul,
                      "/":operator.div,
                      "**":operator.pow}

        # Case of mean or median for Input2 
        if args.median == True:
            value2 = numpy.ma.median(value2)
        elif args.mean == True:
            value2 = numpy.ma.mean(value2)

        oper = operations[args.operation[0]]
        result = numpy.zeros_like(im1)

        result.data[:] = oper(im1.data, value2.data)  # Actual operation of images
        result.mask[:] = im1.mask | value2.mask       # If any is masked, result is masked as well


        # If args.fill_val is present, use it
        if args.fill_val:
            result.data[:] = result.filled(float(args.fill_val))
                    
        # If output exists use it, otherwise use the input. Prefix/suffix might
        # modify things in next step.
        if args.output != '': 
            outpt = os.path.abspath(args.output)
        else:
            outpt = os.path.abspath(operand1)
            
        # Separate (path, file) and (file root, extensions). Then build new name. 
        outdir, outfile = os.path.split(outpt)   
        outfile_root, outfile_ext = re.match(r'(^.*?)(\..*)', outfile).groups()   
        outpt = os.path.join(outdir, args.prefix + outfile_root + args.suffix + 
                             outfile_ext)                         

        # Now name for the mask, if the name exists, use it, otherwise build it.
        if args.mask_name != "":
            mask_name = args.mask_name
        else:
            mask_name = outpt + ".msk"

        # Prepare a header starting from input1 header
        hdr_im = fits.getheader(operand1)
        name2 = os.path.split(operand2)[1]
        if args.median:  # if single number because median used
            name2 = "median(" + name2 + ") (" + str(value2) + ")"
        elif args.mean:  # if single number because mean used
            name2 = "mean(" + name2 + ") (" + str(value) + ")"

        # Write a HISTORY element to the header    
        #hdr_im.add_history(" - Operation performed: " + image1 + " " +
        #                   args.operation[0] + " " + name2)
        try:
            hdr_mask = fits.PrimaryHDU(result.mask.astype(int)).header
        except:
            pass
        hdr_mask.add_history("- Mask corresponding to image: " + outpt)

        # Update the keyword if asked by user
        if args.update and args.keyword:
            old_keyword = hdr_im[args.keyword]
            hdr_im[args.keyword] = (oper(old_keyword, value2.data), "Before: {0}".format(old_keyword) )

        # Now save the resulting image and mask
        if os.path.isfile(outpt):
            os.remove(outpt)
        if os.path.isfile(mask_name):
            os.remove(mask_name)
        fits.writeto(outpt, result.data, header=hdr_im) 
        fits.writeto(mask_name, result.mask.astype(numpy.int0), header=hdr_mask)
        utils.header_update_keyword(outpt, "MASK", os.path.abspath(mask_name),
                                                comment="Name of mask image. ")
        output_list.append(outpt)
    return output_list