示例#1
0
def transform(img, source, target, **kwargs):
    global js,jsName
    if kwargs['Json File'] != jsName:
        js = json.load(open(kwargs['Json File']))
        jsName = kwargs['Json File']
    index = kwargs['index'] if 'index' in kwargs else np.random.randint(0, len(js), 1)[0] #use given, if none given, pick.

    dictionary = None
    if str(index).isdigit(): #see if we are trying to reference by index, else search through values.
        dictionary = js[int(index)]
    else:
        if index in js:
            dictionary = js[index]
        else:
            for d in js:
                if str(index) in d or d in index:
                    dictionary = js[d]
                    break
    if not dictionary:
        raise ValueError("{0} not found in {1}".format(index, jsName))

    result = {}
    result.update(dictionary)
    if 'File Key' in kwargs and kwargs['File Key'] != '':
        if os.path.isfile(dictionary[kwargs['File Key']]):
            openImageFile(dictionary[kwargs['File Key']]).save(target)
            result['file'] = dictionary[kwargs['File Key']]
    return result, None
示例#2
0
    def test_rgb(self):
        filename = self.locateFile('tests/images/test_project5.jpg')
        img_wrapper = image_wrap.openImageFile(filename)
        img = img_wrapper.to_array()
        target_wrapper = image_wrap.ImageWrapper(img)
        filename_output = tempfile.mktemp(prefix='mstcr',
                                          suffix='.png',
                                          dir='.')
        self.filesToKill.extend([filename_output])
        target_wrapper.save(filename_output)

        args, error = plugins.callPlugin('SelectRegion',
                                         img_wrapper,
                                         filename,
                                         filename_output,
                                         alpha='yes')
        wrapper = image_wrap.openImageFile(filename_output)
        output = wrapper.to_array()
        self.assertTrue(sum(sum(output[:, :, 3])) > 255)
        x, y, w, h = widthandheight(output[:, :, 3])
        if x > 1:
            self.assertTrue(sum(sum(output[:, 0:x - 1, 3])) == 0)
        if y > 1:
            self.assertTrue(sum(sum(output[0:y - 1, :, 3])) == 0)
        self.assertTrue(sum(sum(output[y + h + 1:, x + w + 1:, 3])) == 0)
        self.assertEqual(output.shape[0], img.shape[0])
        self.assertEqual(output.shape[1], img.shape[1])
        self.assertTrue('paste_x' in args and args['paste_x'] > 0)
        self.assertTrue('paste_y' in args and args['paste_y'] > 0)
示例#3
0
def transform(img, source, target, **kwargs):
    finalimage = openImageFile(kwargs['Final Image'])
    output = None
    if 'inputmaskname' not in kwargs:
        pastemask, analsys, error = createMask(img, finalimage)
        if error:
            logging.getLogger('maskgen').error("Error creating inputmask " +
                                               error)
        splits = os.path.split(source)
        pastemask.invert()
        pastemask.save(splits[0] + '_inputmask.png')
        pastemask = pastemask.to_array()
        output = {'inputmaskname': splits[0] + '_inputmask.png'}
    else:
        pastemask = openImageFile(kwargs['inputmaskname']).to_array()
    finalimage = finalimage.to_array()
    sourceimg = np.copy(img.to_array()).astype('float')
    if len(pastemask.shape) > 2:
        if pastemask.shape[2] > 3:
            mult = pastemask[:, :, 3] / 255.0
        else:
            mult = pastemask[:, :, 1] / 255.0
    else:
        mult = pastemask / 255.0
    for dim in range(sourceimg.shape[2]):
        sourceimg[:,:,dim] = \
             (sourceimg[:,:,dim]*(1.0-mult)).astype('uint8') + \
             (finalimage[:,:,dim]*(mult)).astype('uint8')
    ImageWrapper(sourceimg.astype('uint8')).save(target)
    return output, None
示例#4
0
 def test_something(self):
     filename = self.locateFile('tests/images/test_project1.jpg')
     wrapper = image_wrap.openImageFile(filename)
     filename_output = tempfile.mktemp(prefix='mstcr',
                                       suffix='.png',
                                       dir='.')
     self.addFileToRemove(filename_output)
     img = numpy.asarray(wrapper)
     image_wrap.ImageWrapper(img).save(filename_output)
     args, error = plugins.callPlugin('WienerFilter',
                                      wrapper,
                                      filename,
                                      filename_output,
                                      percentageChange=0.5)
     wrapper = image_wrap.openImageFile(filename_output)
     output = wrapper.to_array()
     self.assertEqual(output.shape, img.shape)
     diff = abs(output - img)
     finaldiff = numpy.zeros((diff.shape[0], diff.shape[1]))
     for i in range(3):
         finaldiff = finaldiff + diff[:, :, i]
     finaldiff[finaldiff > 0] = 1
     self.assertTrue(
         sum(sum(finaldiff)) /
         (finaldiff.shape[0] * finaldiff.shape[1]) > 0.8)
示例#5
0
 def test_typical(self):
     img_wrapper = image_wrap.openImageFile(
         self.locateFile('tests/images/test.png'))
     img = img_wrapper.to_array()
     img_wrapper = image_wrap.ImageWrapper(img)
     target_wrapper = image_wrap.ImageWrapper(img)
     filename = self.locateFile('tests/images/test.png')
     filename_output = tempfile.mktemp(prefix='mstcr',
                                       suffix='.png',
                                       dir='.')
     self.filesToKill.extend([filename_output])
     target_wrapper.save(filename_output)
     args, error = plugins.callPlugin('SmartMaskSelector',
                                      img_wrapper,
                                      filename,
                                      filename_output,
                                      smallw=100,
                                      smallh=100,
                                      mediumw=150,
                                      mediumh=150,
                                      largew=200,
                                      largeh=200,
                                      size=2,
                                      op=2)
     wrapper = image_wrap.openImageFile(filename_output)
     output = wrapper.to_array()
     self.assertTrue(img_wrapper.size[1] == wrapper.size[1])
     self.assertTrue(img_wrapper.size[0] == wrapper.size[0])
     self.assertTrue(len(output.shape) == 2)
     totalsize = sum(sum(output / 255))
     print totalsize
     self.assertTrue(totalsize <= (1.5 * 22500))
     self.assertTrue(totalsize >= (22500 * 0.5))
     self.assertTrue('paste_x' in args and args['paste_x'] > 0)
     self.assertTrue('paste_y' in args and args['paste_y'] > 0)
示例#6
0
 def xtest_mask_gen(self):
     from maskgen import tool_set
     from maskgen.image_wrap import ImageWrapper
     aorig = image_wrap.openImageFile('tests/images/0c5a0bed2548b1d77717b1fb4d5bbf5a-TGT-17-CLONE.png')
     a = aorig.convert('YCbCr')
     borig = image_wrap.openImageFile('tests/images/0c5a0bed2548b1d77717b1fb4d5bbf5a-TGT-18-CARVE.png')
     b = borig.convert('YCbCr')
     mask = tool_set._tallySeam((a.to_array()[:, :, 0]),
                                 (b.to_array()[20:, :, 0]))
     ImageWrapper(mask).save('seam_mask.png')
示例#7
0
 def test_opacity_analysis(self):
     # need to redo with generated data.
     initialImage = image_wrap.openImageFile(self.locateFile('tests/images/pre_blend.png'))
     finalImage = image_wrap.openImageFile(self.locateFile('tests/images/post_blend.png'))
     mask = image_wrap.openImageFile(self.locateFile('tests/images/blend_mask.png'))
     donorMask = image_wrap.openImageFile(self.locateFile('tests/images/donor_to_blend_mask.png'))
     donorImage = image_wrap.openImageFile(self.locateFile('tests/images/donor_to_blend.png'))
     result = tool_set.generateOpacityImage(initialImage.to_array(), donorImage.to_array(), finalImage.to_array(), mask.to_array(),
                                            donorMask.to_array(),None)
     min = np.min(result)
     max = np.max(result)
     result = (result - min)/(max-min) * 255.0
示例#8
0
 def test_mask_withsame_size(self):
     analyzer = FrameAnalyzer(199.87494824016565, 233.18743961352658, 33.31249137336093)
     f1 = openImageFile(self.locateFile('tests/algorithms/f1.png')).image_array
     f2 = openImageFile(self.locateFile('tests/algorithms/f2.png')).image_array
     analyzer.updateFlow(f1, f2, 'forward')
     flow_manager = OpticalFlow(f1, f2, analyzer.back_flow, analyzer.jump_flow)
     frame = flow_manager.setTime(0.0)
     self.assertEqual(0, np.sum(abs(frame - f1)))
     frame = flow_manager.setTime(0.1)
     self.assertTrue( np.sum(abs(frame - f1)) < np.sum(abs(frame - f2)))
     print np.sum(abs(frame - f2))
     frame = flow_manager.setTime(0.9)
     self.assertTrue(np.sum(abs(frame - f1)) > np.sum(abs(frame - f2)))
     frame = flow_manager.setTime(1.0)
     self.assertEqual(0, np.sum(abs(frame - f2)))
示例#9
0
    def test_noise(self):
        img_wrapper = image_wrap.openImageFile(
            self.locateFile('tests/images/test_project1.jpg'))
        filename_output = tempfile.mktemp(prefix='cstcr',
                                          suffix='.png',
                                          dir='.')
        self.filesToKill.extend([filename_output])
        img_wrapper.save(filename_output)

        args, error = plugins.callPlugin(
            'MagickAddNoise', img_wrapper,
            self.locateFile('tests/images/test_project1.jpg'), filename_output,
            **{"Noise Type": "salt-pepper"})
        wrapper = image_wrap.openImageFile(filename_output)
        output = wrapper.to_array()
        self.assertTrue(output.shape == img_wrapper.to_array().shape)
示例#10
0
def transform(img, source, target, **kwargs):
    # NOTE: arguments passed on AS IS!!
    im = openImageFile(source, args=kwargs)
    imarray = np.array(im)
    #deal with grayscale image
    if len(imarray.shape) == 2:
        w, h = imarray.shape
        ret = np.empty((w, h, 3), dtype=np.uint8)
        ret[:, :, :] = imarray[:, :, np.newaxis]
        imarray = ret

    analysis = {}
    if 'Crop' in kwargs and kwargs['Crop'] == 'yes':
        dims = getExifDimensions(source, crop=True)
        if len(dims) > 0 and imarray.shape[0] != dims[0][0]:
            h = int(imarray.shape[0] - dims[0]) / 2
            w = int(imarray.shape[1] - dims[1]) / 2
            imarray = imarray[h:-h, w:-w]
            analysis['location'] = str((h, w))
    if 'Image Rotated' in kwargs and kwargs['Image Rotated'] == 'yes':
        orientation = exif.getOrientationFromExif(source)
        if orientation is not None:
            analysis.update(exif.rotateAnalysis(orientation))
            imarray = exif.rotateAccordingToExif(imarray,
                                                 orientation,
                                                 counter=True)
    ImageWrapper(imarray).save(target, format='PNG')
    analysis['Image Rotated'] = 'yes' if 'rotation' in analysis else 'no'
    return analysis, None
示例#11
0
def transform(img, source, target, **kwargs):
    img_to_paste = openImageFile(kwargs['donor'])
    pasteregionsize = kwargs['region size'] if 'region size' in kwargs else 1.0
    approach = kwargs['approach'] if 'approach' in kwargs else 'simple'
    segment_algorithm = kwargs[
        'segment'] if 'segment' in kwargs else 'felzenszwalb'

    if pasteregionsize < 1.0:
        dims = (int(img.size[1] * pasteregionsize),
                int(img.size[0] * pasteregionsize))
    else:
        dims = (img.size[1], img.size[0])
    x = (img.size[1] - dims[0]) / 2
    y = (img.size[0] - dims[1]) / 2
    imgarray = np.asarray(img)
    if len(imgarray.shape) > 2:
        newimg = imgarray[x:dims[0] + x, y:dims[1] + y, :]
    else:
        newimg = imgarray[x:dims[0] + x, y:dims[1] + y]

    transform_matrix, out = performPaste(ImageWrapper(newimg), img_to_paste,
                                         approach, segment_algorithm)
    if pasteregionsize < 1.0:
        out2 = np.copy(imgarray)
        if len(imgarray.shape) > 2:
            out2[x:dims[0] + x, y:dims[1] + y, :] = out
        else:
            out2[x:dims[0] + x, y:dims[1] + y] = out
        out = out2
    ImageWrapper(out).save(target)
    return {
        'transform matrix': tool_set.serializeMatrix(transform_matrix)
    } if transform_matrix is not None else None, None
示例#12
0
    def test_shrink(self):
        filename = self.locateFile('tests/algorithms/twins.jpg')
        img = openImageFile(filename)

        #img = openImageFile(filename, False, None)

        somemask = img.to_array()
        somemaskcopy = somemask
        sc = SeamCarver(
            filename, shape=(350, 450), energy_function=SobelFunc()
        )  # mask_filename=self.locateFile('tests/algorithms/cat_mask.png'))
        image, mask = sc.remove_seams()

        #ImageWrapper(image).save(os.path.join(os.path.dirname(filename), 'twins_f.png'))
        #ImageWrapper(mask).save(os.path.join(os.path.dirname(filename), 'twins_m.png'))
        radj, cadj = sc.mask_tracker.save_adjusters('adjusters.png')
        sc.mask_tracker.read_adjusters(radj, cadj)
        sc.mask_tracker.save_neighbors_mask('twins_m.png')
        os.remove(radj)
        os.remove(cadj)
        os.remove('twins_m.png')
        somemask = sc.mask_tracker.move_pixels(somemask)
        #ImageWrapper(somemask).save(os.path.join(os.path.dirname(filename), 'twins_sm.png'))
        self.assertTrue(image.shape == somemask.shape)
        self.assertTrue(np.all(image == somemask))
        self.assertTrue(
            (image.shape[0],
             image.shape[1]) == sc.mask_tracker.neighbors_mask.shape)
        originalmask = sc.mask_tracker.invert_move_pixels(somemask)
        self.assertTrue(somemaskcopy.shape == originalmask.shape)
        #ImageWrapper(somemaskcopy).save(os.path.join(os.path.dirname(filename), 'twins_om.png'))
        #ImageWrapper(originalmask).save(os.path.join(os.path.dirname(filename), 'twins_om2.png'))
        self.assertTrue(
            np.all(somemaskcopy[mask == 0] == originalmask[mask == 0]))
示例#13
0
def run_plugin(argv=None):
    import argparse
    import itertools

    parser = argparse.ArgumentParser(description='')
    parser.add_argument('--plugin', help='name of plugin', required=True)
    parser.add_argument('--input', help='base image or video', required=True)
    parser.add_argument('--output',
                        help='result image or video',
                        required=True)
    parser.add_argument(
        '--arguments',
        nargs='+',
        default={},
        help='Additional operation/plugin arguments e.g. rotation 60')
    args = parser.parse_args()

    op = software_loader.getOperation(getOperation(args.plugin)['name'])
    parsedArgs = dict(
        itertools.izip_longest(*[iter(args.arguments)] * 2, fillvalue=""))
    for key in parsedArgs:
        parsedArgs[key] = validateAndConvertTypedValue(
            key, parsedArgs[key], op, skipFileValidation=False)

    loadPlugins()
    args, msg = callPlugin(args.plugin, openImageFile(args.input), args.input,
                           args.output, **parsedArgs)
    if msg is not None:
        print(msg)
    if args is not None:
        print('Results:')
        print(str(args))
示例#14
0
    def test_something(self):
        img = numpy.random.randint(0, 255, (500, 500, 3), dtype='uint8')
        mask = numpy.zeros((500, 500), dtype='uint8')
        mask[30:50, 30:50] = 255
        self.assertTrue(
            sum(sum(sum(img[30:50, 30:50] - img[400:420, 300:320]))) > 0)
        img_wrapper = image_wrap.ImageWrapper(img)
        target_wrapper = image_wrap.ImageWrapper(mask)
        mask_wrapper = image_wrap.ImageWrapper(mask)
        filename = tempfile.mktemp(prefix='mstc', suffix='.png', dir='.')
        filename_mask = tempfile.mktemp(prefix='mstcm', suffix='.png', dir='.')
        filename_output = tempfile.mktemp(prefix='mstcr',
                                          suffix='.png',
                                          dir='.')
        self.filesToKill.extend([filename, filename_mask, filename_output])
        img_wrapper.save(filename)
        mask_wrapper.save(filename_mask)
        target_wrapper.save(filename_output)

        args, error = plugins.callPlugin('DesignPasteClone',
                                         img_wrapper,
                                         filename,
                                         filename_output,
                                         inputmaskname=filename_mask,
                                         paste_x=300,
                                         paste_y=400)
        wrapper = image_wrap.openImageFile(filename_output)
        output = wrapper.to_array()
        self.assertTrue(
            sum(sum(sum(img[30:50, 30:50] - output[400:420, 300:320]))) == 0)
示例#15
0
 def test_something(self):
     img = numpy.random.randint(0, 255, (500, 500, 3), dtype='uint8')
     wrapper = image_wrap.ImageWrapper(img)
     filename = tempfile.mktemp(prefix='mstc', suffix='.png', dir='.')
     filename_output = tempfile.mktemp(prefix='mstcr',
                                       suffix='.png',
                                       dir='.')
     self.filesToKill.append(filename)
     wrapper.save(filename)
     self.filesToKill.append(filename_output)
     image_wrap.ImageWrapper(img).save(filename_output)
     args, error = plugins.callPlugin('MedianBlur',
                                      wrapper,
                                      filename,
                                      filename_output,
                                      kernelSize=25,
                                      percentageChange=0.5)
     wrapper = image_wrap.openImageFile(filename_output)
     output = wrapper.to_array()
     self.assertEqual(output.shape, img.shape)
     diff = abs(output - img)
     finaldiff = numpy.zeros((500, 500))
     for i in range(3):
         finaldiff = finaldiff + diff[:, :, i]
     finaldiff[finaldiff > 0] = 1
     self.assertTrue(abs(sum(sum(finaldiff)) - 62500) < 100)
示例#16
0
    def test_snap(self):
        img = numpy.zeros((500, 500), dtype='uint8')
        wrapper = image_wrap.ImageWrapper(img)
        filename = tempfile.mktemp(prefix='mstc', suffix='.png', dir='.')
        filename_output = tempfile.mktemp(prefix='mstcr',
                                          suffix='.png',
                                          dir='.')
        self.filesToKill.append(filename)
        wrapper.save(filename)
        self.filesToKill.append(filename_output)
        image_wrap.ImageWrapper(img).save(filename_output)
        args, error = plugins.callPlugin('CropSelector',
                                         wrapper,
                                         filename,
                                         filename_output,
                                         percentage_width=0.1,
                                         percentage_height=0.1,
                                         eightbit_boundary='yes')
        wrapper = image_wrap.openImageFile(filename_output)
        output = wrapper.to_array()

        self.assertEqual(output.shape, img.shape)
        self.assertTrue('crop_x' in args and args['crop_x'] <= 56)
        self.assertTrue('crop_y' in args and args['crop_y'] <= 56)
        self.assertTrue('crop_width' in args and args['crop_width'] == 56)
        self.assertTrue('crop_height' in args and args['crop_height'] == 56)
        self.assertTrue(args['crop_y'] % 8 == 0)
        self.assertTrue(args['crop_x'] % 8 == 0)
        self.assertTrue(
            output[-(args['crop_height'] - args['crop_y'] + 1),
                   -(args['crop_width'] - args['crop_x'] + 1)] == 255)
        self.assertTrue(
            output[-(args['crop_height'] - args['crop_y'] - 1),
                   -(args['crop_width'] - args['crop_x'] - 1)] == 0)
示例#17
0
 def test_seam_carve(self):
     img_wrapper = image_wrap.openImageFile(self.locateFile('tests/images/test_project5.jpg'))
     img = img_wrapper.to_array()
     mask = np.zeros(img.shape).astype('uint8')
     cv2.circle(mask, (img.shape[0]/8,img.shape[1]/8), img.shape[0]/16, (255, 0, 0), -1)
     cv2.circle(mask, (img.shape[0] *5/ 8, img.shape[1] *5/ 8), img.shape[0] / 16, (0, 255, 0), -1)
     mask_wrapper = image_wrap.ImageWrapper(mask)
     mask_output = tempfile.mktemp(prefix='mstcr', suffix='.png', dir='.')
     self.addFileToRemove(mask_output)
     mask_wrapper.save(mask_output)
     target_wrapper = image_wrap.ImageWrapper(img)
     filename  = self.locateFile('tests/images/test_project5.jpg')
     filename_output = tempfile.mktemp(prefix='mstcr', suffix='.jpg', dir='.')
     self.addFileToRemove(filename_output)
     target_wrapper.save(filename_output)
     args,error = plugins.callPlugin('SeamCarve',
                         img_wrapper,
                         filename,
                         filename_output,
                         inputmaskname=os.path.abspath(mask_output),
                         percentage_height=0.95,
                         percentage_width=0.95)
     output_files = args['output_files']
     self.assertTrue('column adjuster' in output_files and os.path.exists(output_files['column adjuster']))
     self.assertTrue('row adjuster' in output_files and os.path.exists(output_files['row adjuster']))
     self.assertTrue('plugin mask' in output_files and os.path.exists(output_files['plugin mask']))
     self.assertTrue('neighbor mask' in output_files and os.path.exists(output_files['neighbor mask']))
     for v in output_files.values():
         os.remove(v)
示例#18
0
    def test_shrink_forward_energy_arch(self):
        #filename = self.locateFile('tests/algorithms/arch_sunset.jpg')
        #newshape = (470, 250)

        filename = self.locateFile('tests/algorithms/pexels-photo-746683.jpg')
        newshape = (1450, 1950)
        img = openImageFile(filename)
        imgcopy = img.to_array()
        sc = SeamCarver(filename,
                        shape=newshape,
                        energy_function=SobelFunc(),
                        seam_function=foward_base_energy_function,
                        keep_size=True)
        image, mask = sc.remove_seams()
        #ImageWrapper(image).save(os.path.join(os.path.dirname(filename), 'as_f.png'))
        #ImageWrapper(mask).save(os.path.join(os.path.dirname(filename), 'as_m.png'))
        #radj, cadj = sc.mask_tracker.save_adjusters('adjusters.png')
        #sc.mask_tracker.read_adjusters( radj, cadj )
        sc.mask_tracker.save_neighbors_mask('as_m.png')
        imgcopymoved = sc.mask_tracker.move_pixels(imgcopy)
        #ImageWrapper(somemask).save(os.path.join(os.path.dirname(filename), 'as_sm.png'))
        self.assertTrue(image.shape == imgcopymoved.shape)
        self.assertTrue(np.all(image == imgcopymoved))
        self.assertTrue(
            (image.shape[0],
             image.shape[1]) == sc.mask_tracker.neighbors_mask.shape)
        originalmask = sc.mask_tracker.invert_move_pixels(imgcopymoved)
        self.assertTrue(imgcopy.shape == originalmask.shape)
        #ImageWrapper(imgcopymoved).save(os.path.join(os.path.dirname(filename), 'as_om.png'))
        #ImageWrapper(originalmask).save(os.path.join(os.path.dirname(filename), 'as_om2.png'))
        self.assertTrue(np.all(imgcopy[mask == 0] == originalmask[mask == 0]))
    def test_compare(self):
        from maskgen import tool_set
        wrapper1 = image_wrap.openImageFile(
            self.locateFile('tests/images/pre_blend.png'))
        arr2 = np.copy(wrapper1.image_array)
        for x in np.random.randint(1, arr2.shape[0] - 1, 100):
            for y in np.random.randint(1, arr2.shape[1] - 1, 100):
                arr2[x, y, 1] = arr2[x, y, 1] + np.random.randint(-20, 20)
        arr2[100:200, 100:200, 2] = arr2[100:200, 100:200, 2] - 25
        wrapper2 = image_wrap.ImageWrapper(arr2)

        args = [{
            'aggregate': 'luminance',
            'minimum threshold': 3,
            "weight": 4
        }, {
            'aggregate': 'luminance',
            'minimum threshold': 3,
            "weight": 1
        }, {
            'aggregate': 'max'
        }]
        for arg in args:
            result = tool_set.mediatedCompare(
                wrapper1.to_array().astype('int16'),
                wrapper2.to_array().astype('int16'),
                arguments=arg)
            self.assertTrue(np.all(result[0][100:200, 100:200] == 255))
            result[0][100:200, 100:200] = 0
            self.assertTrue(np.all(result[0] == 0))
示例#20
0
def find_segmentation_classifier(image_name, segmentation_directory):
    import os
    real_name = os.path.split(image_name)[0]
    dotpos = min(33, real_name.find('.'))
    real_name = real_name[0:dotpos]
    segment_name = os.path.join(segmentation_directory, real_name + '.png')
    return image_wrap.openImageFile(segment_name) if os.path.exists(
        segment_name) else None
示例#21
0
def transform(img, source, target, **kwargs):
    donor = kwargs['donor']  # raise error if missing donor

    im_source = openImageFile(source).image_array
    im_donor_trace = openImageFile(donor).image_array

    if np.shape(im_source)[0:2] != np.shape(im_donor_trace)[0:2]:
        orientation_source = np.shape(im_source)[0] - np.shape(im_source)[1]
        orientation_donor = np.shape(im_donor_trace)[0] - np.shape(
            im_donor_trace)[1]
        if sign(orientation_source) != sign(orientation_donor):
            im_donor_trace = np.rot90(im_donor_trace, -1)
        location, im_source = centeredCrop(im_source, im_donor_trace)
        ImageWrapper(im_source).save(target, format='PNG')
    else:
        location = (0, 0)
    return {'location': location}, None
示例#22
0
    def test_gamma(self):
        img_wrapper = image_wrap.openImageFile(
            self.locateFile('tests/images/test_project1.jpg'))
        filename_output = tempfile.mktemp(prefix='cstcr',
                                          suffix='.png',
                                          dir='.')
        self.filesToKill.extend([filename_output])
        img_wrapper.save(filename_output)

        args, error = plugins.callPlugin(
            'ManualGammaCorrection',
            img_wrapper,
            self.locateFile('tests/images/test_project1.jpg'),
            filename_output,
            gamma=2.0)
        wrapper = image_wrap.openImageFile(filename_output)
        output = wrapper.to_array()
        self.assertTrue(output.shape == img_wrapper.to_array().shape)
示例#23
0
def transform(img, source, target, **kwargs):
    donor = kwargs['donor']
    sizSource = img.size
    sizDonor = openImageFile(donor).size
    validateImageSizes(sizSource, sizDonor)
    # Use Liquid Rescale to resize donor image
    # to size of source image.
    resizeUsingLQR(target, sizDonor)
    return None, None
示例#24
0
def transform(img, source, target, **kwargs):
    channel_map = {"red": 0, "green": 1, "blue": 2}
    donor = kwargs['mask'] if 'mask' in kwargs else source
    channel_name = kwargs['channel'] if 'channel' in kwargs else "green"
    img = openImageFile(donor)
    color_im = np.zeros((img.size[1], img.size[0], 3), dtype=np.uint8)
    color_im[:, :, channel_map[channel_name]] = img.image_array
    ImageWrapper(color_im).save(target)
    return None, None
示例#25
0
    def test_contrast(self):
        img_wrapper = image_wrap.openImageFile(
            self.locateFile('tests/images/test_project1.jpg'))
        filename_output = tempfile.mktemp(prefix='cstcr',
                                          suffix='_c.png',
                                          dir='.')
        self.filesToKill.extend([filename_output])
        img_wrapper.save(filename_output)

        args, error = plugins.callPlugin(
            'Constrast',
            img_wrapper,
            self.locateFile('tests/images/test_project1.jpg'),
            filename_output,
            direction="increase")
        wrapper = image_wrap.openImageFile(filename_output)
        output = wrapper.to_array()
        self.assertTrue(output.shape == img_wrapper.to_array().shape)
示例#26
0
 def check_save(self, wrapper, foarmat):
     dir = os.path.dirname(self.locateFile('tests/images/postfill.png'))
     fname = os.path.join(dir,
                          'foo.' + ('tif' if foarmat != 'PNG' else 'png'))
     self.addFileToRemove(fname)
     wrapper.save(fname, format=foarmat)
     compareWrapper = image_wrap.openImageFile(fname)
     self.assertTrue(
         (compareWrapper.image_array == wrapper.image_array).all())
示例#27
0
 def test_two_channel(self):
     wrapper = image_wrap.openImageFile(
         self.locateFile('tests/images/two_channel.jpg'))
     wrapper.to_mask()
     wrapper.apply_transparency()
     wrapper.convert('L')
     wrapper.convert('RGBA')
     wrapper.to_float()
     wrapper.to_rgb()
示例#28
0
 def draw(self, frame, filename):
     from maskgen.analytics.analysis import ela
     im = ela(openImageFile(filename))
     photo = ImageTk.PhotoImage(
         fixTransparency(imageResize(im, (400, 400))).toPIL())
     canvas = Canvas(frame, width=400, height=400)
     canvas.create_image(0, 0, image=photo, anchor=NW)
     canvas.grid(row=0, column=0)
     return (im, photo)
示例#29
0
    def test_modulate(self):
        img_wrapper = image_wrap.openImageFile(
            self.locateFile('tests/images/test_project1.jpg'))
        filename_output = tempfile.mktemp(prefix='cstcr',
                                          suffix='.png',
                                          dir='.')
        self.filesToKill.extend([filename_output])
        img_wrapper.save(filename_output)

        args, error = plugins.callPlugin(
            'MagickModulate',
            img_wrapper,
            self.locateFile('tests/images/test_project1.jpg'),
            filename_output,
            saturation=130,
            brightness=130)
        wrapper = image_wrap.openImageFile(filename_output)
        output = wrapper.to_array()
        self.assertTrue(output.shape == img_wrapper.to_array().shape)
示例#30
0
def transform(img, source, target, **kwargs):
    rgba = img.convert('RGBA')
    donor_img_file = kwargs['donor']
    inputmask = openImageFile(donor_img_file)
    donor = inputmask.convert('RGBA')
    if donor.size != rgba.size:
        donor = donor.resize(rgba.size, Image.ANTIALIAS)
    rgba.paste(donor, (0, 0), donor)
    rgba.save(target)
    return None, None