MATLAB: How to center the non-empty pixels of a png image in its frame

image analysisimage processingImage Processing ToolboxMATLAB

Hi all. I have a bunch of png images that look like the one that I am attaching in this question. They all have the same frame dimensions. Most of the pixels are zero-valued (i.e. transparent) and the actual content are at the bottom right of the frame, which makes a small portion of the frame.
My question is, can I move this object to the center of the frame without changing the frame size? I would also like the rest of the pixels to still stay transparent.
I have access to the Image Processing Toolbox, so solutions using that would also be very helpful.
Many thanks!

Best Answer

You might perhaps be able to simplify the centering logic.
filename = 'https://www.mathworks.com/matlabcentral/answers/uploaded_files/665090/image.png';
[img, ~, alphamap] = imread(filename);
h = imshow(img); h.AlphaData = alphamap;
set(gca,'visible','on')
title('original')
mask1 = any(alphamap,1);
first_col = find(mask1,1)
first_col = 980
last_col = find(mask1,1,'last')
last_col = 1227
mask2 = any(alphamap,2);
first_row = find(mask2,1)
first_row = 831
last_row = find(mask2,1,'last')
last_row = 1092
col_span = last_col - first_col + 1
col_span = 248
row_span = last_row - first_row + 1
row_span = 262
[nrow, ncol, ~] = size(img)
nrow = 1092
ncol = 1236
top_target_row = floor((nrow - row_span)/2)
top_target_row = 415
left_target_col = floor((ncol - col_span)/2)
left_target_col = 494
row_shift = top_target_row - first_row
row_shift = -416
col_shift = left_target_col - first_col
col_shift = -486
shifted_img = circshift(img, [row_shift, col_shift]);
shifted_alpha = circshift(alphamap, [row_shift, col_shift]);
h = imshow(shifted_img); h.AlphaData = shifted_alpha;
set(gca,'visible','on')
title('shifted')