MATLAB: Crop a image using ‘imfreehand’ and move the cropped region to the center of black background

centercropped roiImage Processing Toolboxmatlab 2007

I've cropped an ROI with imfreehand() and plotted the center of it using mean (position of cropped region). Then I've plotted the center of completely black image. For the resulting image to have the cropped image at center of black background, is it OK to map the marked centers of both images, or get positions for moving the region manually? I want to do this for multiple images, so is it possible to apply any formula or function? Also I've attached example images and sample output. Kindly help me in this.
I've tried also tried using circular shift, circshift(), for moving the cropped portion to the center of black background, but it is not working. Applying a circular shift made the ROI to move like half portion up an remaining down the center of black image. Why did it appear so?
Original Image:
ROI with centroid marked:
Center of black image:
Desired output image:
Thank you and have a Good Day.

Best Answer

It's not obvious, but you can use imwarp() instead of circshift. See this demo:
% Shifts / translates an image to the right by 500 pixels and down by 200 pixels.
% Area shifted in is black.
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 20;
grayImage = imread('concordorthophoto.png');
[rows, columns, numberOfColorChannels] = size(grayImage);
subplot(1, 2, 1);
imshow(grayImage);
axis on;
title('Original Image', 'fontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 1 1]);
deltaX = 500; % Shift x by 500 pixels.

deltaY = 200; % Shift y by 200 pixels.
D = zeros(rows, columns, 2);
D(:,:,1) = -deltaX; % Shift x by 500 pixels.
D(:,:,2) = -deltaY; % Shift x by 200 pixels.
warpedImage = imwarp(grayImage, D);
subplot(1, 2, 2);
imshow(warpedImage);
axis on;
title('Shifted Image', 'fontSize', fontSize);
So just mask the image in place (see attached demo script freehand_masking_demo.m), then do the shifting with imwarp().