Given two input images create and display an image where the two have been overlayed on top of each other.
161853
public static <T extends ImageGray<T>>
	void stitch( BufferedImage imageA , BufferedImage imageB , Class<T> imageType )
	{
		T inputA = ConvertBufferedImage.convertFromSingle(imageA, null, imageType);
		T inputB = ConvertBufferedImage.convertFromSingle(imageB, null, imageType);

		// Detect using the standard SURF feature descriptor and describer
		DetectDescribePoint detDesc = FactoryDetectDescribe.surfStable(
				new ConfigFastHessian(1, 2, 200, 1, 9, 4, 4), null,null, imageType);
		ScoreAssociation<BrightFeature> scorer = FactoryAssociation.scoreEuclidean(BrightFeature.class,true);
		AssociateDescription<BrightFeature> associate = FactoryAssociation.greedy(scorer,2,true);

		// fit the images using a homography.  This works well for rotations and distant objects.
		ModelMatcher<Homography2D_F64,AssociatedPair> modelMatcher =
				FactoryMultiViewRobust.homographyRansac(null,new ConfigRansac(60,3));

		Homography2D_F64 H = computeTransform(inputA, inputB, detDesc, associate, modelMatcher);

		renderStitching(imageA,imageB,H);
	}
138445
public static void checkReshape(ImageBase<?> imgA, ImageBase<?> imgB) {
		if( imgA == imgB )
			throw new IllegalArgumentException("Image's can't be the same instance");
		imgB.reshape(imgA.width,imgA.height);
	}
1043310
public static void checkReshapeB(ImageMultiBand<?> imgA, ImageMultiBand<?> imgB) {
		if( imgA == imgB )
			throw new IllegalArgumentException("Image's can't be the same instance");
		imgB.reshape(imgA.width,imgA.height,imgA.getNumBands());
	}
615359
def plot_ortho_stack(images, overlays=None, reorient=True,
    # xyz arguments
    xyz=None, xyz_lines=False, xyz_color='red', xyz_alpha=0.6, xyz_linewidth=2, xyz_pad=5,
    # base image arguments
    cmap='Greys_r', alpha=1,
    # overlay arguments
    overlay_cmap='jet', overlay_alpha=0.9, 
    # background arguments
    black_bg=True, bg_thresh_quant=0.01, bg_val_quant=0.99, 
    # scale/crop/domain arguments
    crop=False, scale=False, domain_image_map=None, 
    # title arguments
    title=None, titlefontsize=24, title_dx=0, title_dy=0, 
    # 4th panel text arguemnts
    text=None, textfontsize=24, textfontcolor='white', text_dx=0, text_dy=0,
    # save & size arguments
    filename=None, dpi=500, figsize=1., colpad=0, rowpad=0,
    transpose=False, transparent=True):
    
    def mirror_matrix(x):
        return x[::-1,:]
    def rotate270_matrix(x):
        return mirror_matrix(x.T)
    def reorient_slice(x, axis):
        return rotate270_matrix(x)

    # need this hack because of a weird NaN warning from matplotlib with overlays
    warnings.simplefilter('ignore')

    n_images = len(images)

    # handle `image` argument
    for i in range(n_images):
        if isinstance(images[i], str):
            images[i] = iio2.image_read(images[i])
        if not isinstance(images[i], iio.ANTsImage):
            raise ValueError('image argument must be an ANTsImage')
        if images[i].dimension != 3:
            raise ValueError('Input image must have 3 dimensions!')

    if overlays is None:
        overlays = [None]*n_images
    # handle `overlay` argument
    for i in range(n_images):
        if overlays[i] is not None:
            if isinstance(overlays[i], str):
                overlays[i] = iio2.image_read(overlays[i])
            if not isinstance(overlays[i], iio.ANTsImage):
                raise ValueError('overlay argument must be an ANTsImage')
            if overlays[i].dimension != 3:
                raise ValueError('Overlay image must have 3 dimensions!')

            if not iio.image_physical_space_consistency(images[i], overlays[i]):
                overlays[i] = reg.resample_image_to_target(overlays[i], images[i], interp_type='linear')

    for i in range(1,n_images):
        if not iio.image_physical_space_consistency(images[0], images[i]):
            images[i] = reg.resample_image_to_target(images[0], images[i], interp_type='linear')

    # reorient images
    if reorient != False:
        if reorient == True:
            reorient = 'RPI'
        
        for i in range(n_images):
            images[i] = images[i].reorient_image2(reorient)
        
        if overlays[i] is not None:
            overlays[i] = overlays[i].reorient_image2(reorient)

    # handle `slices` argument
    if xyz is None:
        xyz = [int(s/2) for s in images[0].shape]
    for i in range(3):
        if xyz[i] is None:
            xyz[i] = int(images[0].shape[i]/2)

    # resample image if spacing is very unbalanced
    spacing = [s for i,s in enumerate(images[0].spacing)]
    if (max(spacing) / min(spacing)) > 3.:
        new_spacing = (1,1,1)
        for i in range(n_images):
            images[i] = images[i].resample_image(tuple(new_spacing))
        if overlays[i] is not None:
            overlays[i] = overlays[i].resample_image(tuple(new_spacing))
        xyz = [int(sl*(sold/snew)) for sl,sold,snew in zip(xyz,spacing,new_spacing)]

    # potentially crop image
    if crop:
        for i in range(n_images):
            plotmask = images[i].get_mask(cleanup=0)
            if plotmask.max() == 0:
                plotmask += 1
            images[i] = images[i].crop_image(plotmask)
            if overlays[i] is not None:
                overlays[i] = overlays[i].crop_image(plotmask)
                
    # pad images
    for i in range(n_images):
        if i == 0:
            images[i], lowpad, uppad = images[i].pad_image(return_padvals=True)
        else:
            images[i] = images[i].pad_image()
        if overlays[i] is not None:
            overlays[i] = overlays[i].pad_image()
    xyz = [v+l for v,l in zip(xyz,lowpad)]

    # handle `domain_image_map` argument
    if domain_image_map is not None:
        if isinstance(domain_image_map, iio.ANTsImage):
            tx = tio2.new_ants_transform(precision='float', transform_type='AffineTransform',
                                         dimension=3)
            for i in range(n_images):
                images[i] = tio.apply_ants_transform_to_image(tx, images[i], domain_image_map)
            
                if overlays[i] is not None:
                    overlays[i] = tio.apply_ants_transform_to_image(tx, overlays[i], 
                                                            domain_image_map, 
                                                            interpolation='linear')       
        elif isinstance(domain_image_map, (list, tuple)):
            # expect an image and transformation
            if len(domain_image_map) != 2:
                raise ValueError('domain_image_map list or tuple must have length == 2')
            
            dimg = domain_image_map[0]
            if not isinstance(dimg, iio.ANTsImage):
                raise ValueError('domain_image_map first entry should be ANTsImage')

            tx = domain_image_map[1]
            for i in range(n_images):
                images[i] = reg.apply_transforms(dimg, images[i], transform_list=tx)
                if overlays[i] is not None:
                    overlays[i] = reg.apply_transforms(dimg, overlays[i], transform_list=tx,
                                                   interpolator='linear')

    # potentially find dynamic range
    if scale == True:
        vmins = []
        vmaxs = []
        for i in range(n_images):
            vmin, vmax = images[i].quantile((0.05,0.95))
            vmins.append(vmin)
            vmaxs.append(vmax)
    elif isinstance(scale, (list,tuple)):
        if len(scale) != 2:
            raise ValueError('scale argument must be boolean or list/tuple with two values')
        vmins = []
        vmaxs = []
        for i in range(n_images):
            vmin, vmax = images[i].quantile(scale)
            vmins.append(vmin)
            vmaxs.append(vmax)
    else:
        vmin = None
        vmax = None

    if not transpose:
        nrow = n_images
        ncol = 3
    else:
        nrow = 3
        ncol = n_images

    fig = plt.figure(figsize=((ncol+1)*2.5*figsize, (nrow+1)*2.5*figsize))
    if title is not None:
        basey = 0.93
        basex = 0.5
        fig.suptitle(title, fontsize=titlefontsize, x=basex+title_dx, y=basey+title_dy)

    if (colpad > 0) and (rowpad > 0):
        bothgridpad = max(colpad, rowpad)
        colpad = 0
        rowpad = 0
    else:
        bothgridpad = 0.0

    gs = gridspec.GridSpec(nrow, ncol, wspace=bothgridpad, hspace=0.0,
                 top=1.-0.5/(nrow+1), bottom=0.5/(nrow+1) + colpad, 
                 left=0.5/(ncol+1) + rowpad, right=1-0.5/(ncol+1))

    # pad image to have isotropic array dimensions
    for i in range(n_images):
        images[i] = images[i].numpy()
        if overlays[i] is not None:
            overlays[i] = overlays[i].numpy()
            overlays[i][np.abs(overlays[i]) == 0] = np.nan

    ####################
    ####################
    for i in range(n_images):
        yz_slice = reorient_slice(images[i][xyz[0],:,:],0)
        if not transpose:
            ax = plt.subplot(gs[i,0])
        else:
            ax = plt.subplot(gs[0,i])
        ax.imshow(yz_slice, cmap=cmap, vmin=vmin, vmax=vmax)
        if overlays[i] is not None:
            yz_overlay = reorient_slice(overlays[i][xyz[0],:,:],0)
            ax.imshow(yz_overlay, alpha=overlay_alpha, cmap=overlay_cmap)
        if xyz_lines:
            # add lines
            l = mlines.Line2D([yz_slice.shape[0]-xyz[1],yz_slice.shape[0]-xyz[1]], 
                              [xyz_pad,yz_slice.shape[0]-xyz_pad],
                              color=xyz_color, alpha=xyz_alpha, linewidth=xyz_linewidth)
            ax.add_line(l)
            l = mlines.Line2D([xyz_pad,yz_slice.shape[1]-xyz_pad], 
                              [yz_slice.shape[1]-xyz[2],yz_slice.shape[1]-xyz[2]],
                color=xyz_color, alpha=xyz_alpha, linewidth=xyz_linewidth)
            ax.add_line(l)
        ax.axis('off')
        ####################
        ####################

        xz_slice = reorient_slice(images[i][:,xyz[1],:],1)
        if not transpose:
            ax = plt.subplot(gs[i,1])
        else:
            ax = plt.subplot(gs[1,i])
        ax.imshow(xz_slice, cmap=cmap, vmin=vmin, vmax=vmax)
        if overlays[i] is not None:
            xz_overlay = reorient_slice(overlays[i][:,xyz[1],:],1)
            ax.imshow(xz_overlay, alpha=overlay_alpha, cmap=overlay_cmap)
        if xyz_lines:
            # add lines
            l = mlines.Line2D([xz_slice.shape[0]-xyz[0],xz_slice.shape[0]-xyz[0]], 
                              [xyz_pad,xz_slice.shape[0]-xyz_pad],
                               color=xyz_color, alpha=xyz_alpha, linewidth=xyz_linewidth)
            ax.add_line(l)
            l = mlines.Line2D([xyz_pad,xz_slice.shape[1]-xyz_pad], 
                              [xz_slice.shape[1]-xyz[2],xz_slice.shape[1]-xyz[2]],
                              color=xyz_color, alpha=xyz_alpha, linewidth=xyz_linewidth)
            ax.add_line(l)
        ax.axis('off')

        ####################
        ####################
        xy_slice = reorient_slice(images[i][:,:,xyz[2]],2)
        if not transpose:
            ax = plt.subplot(gs[i,2])
        else:
            ax = plt.subplot(gs[2,i])
        ax.imshow(xy_slice, cmap=cmap, vmin=vmin, vmax=vmax)
        if overlays[i] is not None:
            xy_overlay = reorient_slice(overlays[i][:,:,xyz[2]],2)
            ax.imshow(xy_overlay, alpha=overlay_alpha, cmap=overlay_cmap)
        if xyz_lines:
            # add lines
            l = mlines.Line2D([xy_slice.shape[0]-xyz[0],xy_slice.shape[0]-xyz[0]], 
                              [xyz_pad,xy_slice.shape[0]-xyz_pad],
                              color=xyz_color, alpha=xyz_alpha, linewidth=xyz_linewidth)
            ax.add_line(l)
            l = mlines.Line2D([xyz_pad,xy_slice.shape[1]-xyz_pad], 
                              [xy_slice.shape[1]-xyz[1],xy_slice.shape[1]-xyz[1]],
                              color=xyz_color, alpha=xyz_alpha, linewidth=xyz_linewidth)
            ax.add_line(l)
        ax.axis('off')

    ####################
    ####################

    if filename is not None:
        plt.savefig(filename, dpi=dpi, transparent=transparent)
        plt.close(fig)
    else:
        plt.show()

    # turn warnings back to default
    warnings.simplefilter('default')
923846
def check_images(img_spec1, img_spec2, bkground_thresh=0.05):
    """"""

    img1 = read_image(img_spec1, bkground_thresh)
    img2 = read_image(img_spec2, bkground_thresh)

    if img1.shape != img2.shape:
        raise ValueError('size mismatch! First image: {} Second image: {}\n'
                         'Two images to be compared must be of the same size in all dimensions.'.format(
            img1.shape,
            img2.shape))

    return img1, img2
578018
function( img ){
    var gl = this.gl;

    this.width  = img.width;
    this.height = img.height;

    gl.bindTexture( T2D, this.id );
    gl.texImage2D(  T2D, 0, this.internal, this.format, this.type, img );
  }
129312
def new_image(cols, rows, *fill, &info_blk)
      self << Magick::Image.new(cols, rows, *fill, &info_blk)
    end
973363
def image2surface(img):
    
    if not CAIRO_AVAILABLE:
        raise Exception("Cairo not available(). image2surface() cannot work.")

    # TODO(Jflesch): Python 3 problem
    # cairo.ImageSurface.create_for_data() raises NotImplementedYet ...

    # img.putalpha(256)
    # (width, height) = img.size
    # imgd = img.tobytes('raw', 'BGRA')
    # imga = array.array('B', imgd)
    # stride = width * 4
    #  return cairo.ImageSurface.create_for_data(
    #      imga, cairo.FORMAT_ARGB32, width, height, stride)

    # So we fall back to this method:
    global g_lock
    with g_lock:
        img_io = io.BytesIO()
        img.save(img_io, format="PNG")
        img_io.seek(0)
        return cairo.ImageSurface.create_from_png(img_io)
586543
def color_replace(color1, color2)

      newimage = self.dup
      newimage.color_replace!(color1,color2)
      newimage
    end
1275657
public void and(final RoaringBitmap x2) {
    int pos1 = 0, pos2 = 0, intersectionSize = 0;
    final int length1 = highLowContainer.size(), length2 = x2.highLowContainer.size();

    while (pos1 < length1 && pos2 < length2) {
      final short s1 = highLowContainer.getKeyAtIndex(pos1);
      final short s2 = x2.highLowContainer.getKeyAtIndex(pos2);
      if (s1 == s2) {
        final Container c1 = highLowContainer.getContainerAtIndex(pos1);
        final Container c2 = x2.highLowContainer.getContainerAtIndex(pos2);
        final Container c = c1.iand(c2);
        if (!c.isEmpty()) {
          highLowContainer.replaceKeyAndContainerAtIndex(intersectionSize++, s1, c);
        }
        ++pos1;
        ++pos2;
      } else if (Util.compareUnsigned(s1, s2) < 0) { // s1 < s2
        pos1 = highLowContainer.advanceUntil(s2, pos1);
      } else { // s1 > s2
        pos2 = x2.highLowContainer.advanceUntil(s1, pos2);
      }
    }
    highLowContainer.resize(intersectionSize);
  }
420390
public BufferedImage createDiffImage(BufferedImage firstImage,
			BufferedImage secondImage) throws IOException {
		BufferedImage diffImage = new BufferedImage(firstImage.getWidth(),
				firstImage.getHeight(), IMAGE_TYPE);

		for (int x = 0; x < firstImage.getWidth() && x < secondImage.getWidth(); x++) {
			for (int y = 0; y < firstImage.getHeight()
					&& y < secondImage.getHeight(); y++) {
				int pixelA = firstImage.getRGB(x, y);
				int pixelB = secondImage.getRGB(x, y);
				int diffRGB = Math.abs(pixelA - pixelB);
				diffImage.setRGB(x, y, diffRGB);
			}
		}
		return diffImage;
	}
641
public static <T extends ImageBase<T>, O extends ImageBase>
	void add(T inputA, T inputB, O output) {
		if( inputA instanceof ImageGray) {
			if (GrayU8.class == inputA.getClass()) {
				PixelMath.add((GrayU8) inputA, (GrayU8) inputB, (GrayU16) output);
			} else if (GrayS8.class == inputA.getClass()) {
				PixelMath.add((GrayS8) inputA, (GrayS8) inputB, (GrayS16) output);
			} else if (GrayU16.class == inputA.getClass()) {
				PixelMath.add((GrayU16) inputA, (GrayU16) inputB, (GrayS32) output);
			} else if (GrayS16.class == inputA.getClass()) {
				PixelMath.add((GrayS16) inputA, (GrayS16) inputB, (GrayS32) output);
			} else if (GrayS32.class == inputA.getClass()) {
				PixelMath.add((GrayS32) inputA, (GrayS32) inputB, (GrayS32) output);
			} else if (GrayS64.class == inputA.getClass()) {
				PixelMath.add((GrayS64) inputA, (GrayS64) inputB, (GrayS64) output);
			} else if (GrayF32.class == inputA.getClass()) {
				PixelMath.add((GrayF32) inputA, (GrayF32) inputB, (GrayF32) output);
			} else if (GrayF64.class == inputA.getClass()) {
				PixelMath.add((GrayF64) inputA, (GrayF64) inputB, (GrayF64) output);
			} else {
				throw new IllegalArgumentException("Unknown image Type: " + inputA.getClass().getSimpleName());
			}
		} else if (inputA instanceof Planar) {
			Planar inA = (Planar)inputA;
			Planar inB = (Planar)inputB;
			Planar out = (Planar)output;

			for (int i = 0; i < inA.getNumBands(); i++) {
				add(inA.getBand(i),inB.getBand(i),out.getBand(i));
			}
		}
	}
815075
def copy_image_on_background(image, color=WHITE):
    
    background = Image.new("RGB", image.size, color)
    background.paste(image, mask=image.split()[3])
    return background
19748
public static void imageToTensor(Planar<GrayF32> input , Tensor_F32 output , int miniBatch) {
		if( input.isSubimage())
			throw new RuntimeException("Subimages not accepted");
		if( output.getDimension() != 4 )
			throw new IllegalArgumentException("Output should be 4-DOF.  batch + spatial (channel,height,width)");
		if( output.length(1) != input.getNumBands() )
			throw new IllegalArgumentException("Number of bands don't match");
		if( output.length(2) != input.getHeight() )
			throw new IllegalArgumentException("Spatial height doesn't match");
		if( output.length(3) != input.getWidth() )
			throw new IllegalArgumentException("Spatial width doesn't match");

		for (int i = 0; i < input.getNumBands(); i++) {
			GrayF32 band = input.getBand(i);
			int indexOut = output.idx(miniBatch,i,0,0);

			int length = input.width*input.height;
			System.arraycopy(band.data, 0,output.d,indexOut,length);
		}
	}
210335
def fill(self, background_shape, img):
        
        background_shape = tuple(background_shape)
        return self._fill(background_shape, img)
688403
public static void renderStitching( BufferedImage imageA, BufferedImage imageB ,
										Homography2D_F64 fromAtoB )
	{
		// specify size of output image
		double scale = 0.5;

		// Convert into a BoofCV color format
		Planar<GrayF32> colorA =
				ConvertBufferedImage.convertFromPlanar(imageA, null, true, GrayF32.class);
		Planar<GrayF32> colorB =
				ConvertBufferedImage.convertFromPlanar(imageB, null,true, GrayF32.class);

		// Where the output images are rendered into
		Planar<GrayF32> work = colorA.createSameShape();

		// Adjust the transform so that the whole image can appear inside of it
		Homography2D_F64 fromAToWork = new Homography2D_F64(scale,0,colorA.width/4,0,scale,colorA.height/4,0,0,1);
		Homography2D_F64 fromWorkToA = fromAToWork.invert(null);

		// Used to render the results onto an image
		PixelTransformHomography_F32 model = new PixelTransformHomography_F32();
		InterpolatePixelS<GrayF32> interp = FactoryInterpolation.bilinearPixelS(GrayF32.class, BorderType.ZERO);
		ImageDistort<Planar<GrayF32>,Planar<GrayF32>> distort =
				DistortSupport.createDistortPL(GrayF32.class, model, interp, false);
		distort.setRenderAll(false);

		// Render first image
		model.set(fromWorkToA);
		distort.apply(colorA,work);

		// Render second image
		Homography2D_F64 fromWorkToB = fromWorkToA.concat(fromAtoB,null);
		model.set(fromWorkToB);
		distort.apply(colorB,work);

		// Convert the rendered image into a BufferedImage
		BufferedImage output = new BufferedImage(work.width,work.height,imageA.getType());
		ConvertBufferedImage.convertTo(work,output,true);

		Graphics2D g2 = output.createGraphics();

		// draw lines around the distorted image to make it easier to see
		Homography2D_F64 fromBtoWork = fromWorkToB.invert(null);
		Point2D_I32 corners[] = new Point2D_I32[4];
		corners[0] = renderPoint(0,0,fromBtoWork);
		corners[1] = renderPoint(colorB.width,0,fromBtoWork);
		corners[2] = renderPoint(colorB.width,colorB.height,fromBtoWork);
		corners[3] = renderPoint(0,colorB.height,fromBtoWork);

		g2.setColor(Color.ORANGE);
		g2.setStroke(new BasicStroke(4));
		g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		g2.drawLine(corners[0].x,corners[0].y,corners[1].x,corners[1].y);
		g2.drawLine(corners[1].x,corners[1].y,corners[2].x,corners[2].y);
		g2.drawLine(corners[2].x,corners[2].y,corners[3].x,corners[3].y);
		g2.drawLine(corners[3].x,corners[3].y,corners[0].x,corners[0].y);

		ShowImages.showWindow(output,"Stitched Images", true);
	}
570451
def _findOverlap(self, img_rgb, overlap, overlapDeviation,
                     rotation, rotationDeviation):
        '''
        
        '''
        # get gray images
        if len(img_rgb.shape) != len(img_rgb.shape):
            raise Exception(
                'number of channels(colors) for both images different')
        if overlapDeviation == 0 and rotationDeviation == 0:
            return (0, overlap, rotation)

        s = self.base_img_rgb.shape
        ho = int(round(overlap * 0.5))
        overlap = int(round(overlap))
        # create two image cuts to compare:
        imgcut = self.base_img_rgb[s[0] - overlapDeviation - overlap:, :]
        template = img_rgb[:overlap, ho:s[1] - ho]

        def fn(angle):
            rotTempl = self._rotate(template, angle)
            # Apply template Matching
            fn.res = cv2.matchTemplate(rotTempl.astype(np.float32),
                                       imgcut.astype(np.float32),
                                       cv2.TM_CCORR_NORMED)
            return 1 / fn.res.mean()

        if rotationDeviation == 0:
            angle = rotation
            fn(rotation)

        else:
            # find best rotation angle:
            angle = brent(fn, brack=(rotation - rotationDeviation,
                                     rotation + rotationDeviation))

        loc = cv2.minMaxLoc(fn.res)[-1]

        offsx = int(round(loc[0] - ho))
        offsy = overlapDeviation + overlap - loc[1]
        return offsx, offsy, angle