필터 지우기
필터 지우기

blockproc loop for image splitting

조회 수: 2 (최근 30일)
Dinyar
Dinyar 2012년 3월 30일
댓글: Walter Roberson 2017년 3월 14일
Hi, I am having trouble splitting a 7383x481 image into 23 321x481 images. I have written this code to be run once the image is loaded as imageA:
for i=1:23
fun = @(block_struct) block_struct(i).data;
name=sprintf('image%i.tif',i);
blockproc(imageA,[321 481],fun,'Destination',name);
end
but it returns an error 'Index exceeds matrix dimensions'. I think I am using block_stuct(i).data incorrectly? Could anyone help me change my code so that I can split the image and save the resutling smaller images?
Thanks for any help!
  댓글 수: 1
Dinyar
Dinyar 2012년 3월 30일
I also tried:
fun = @(block_struct) block_struct.data(i);
This did run and save 23 images but they were all 16x2 images. Very confused.

댓글을 달려면 로그인하십시오.

채택된 답변

Image Analyst
Image Analyst 2012년 3월 30일
Actually I don't know why you're messing with the complication of blockproc when you can use just regular indexing to extract the smaller images and that's A LOT simpler. See this demo I wrote for you:
clc; % Clear the command window.
format compact;
workspace; % Make sure the workspace panel is showing.
fontSize = 20;
% Read in a standard MATLAB gray scale demo image.
folder = fullfile(matlabroot, '\toolbox\images\imdemos');
baseFileName = 'cameraman.tif';
% Get the full filename, with path prepended.
fullFileName = fullfile(folder, baseFileName);
if ~exist(fullFileName, 'file')
% Didn't find it there. Check the search path for it.
fullFileName = baseFileName; % No path this time.
if ~exist(fullFileName, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
grayImage = imread(fullFileName);
% Get the dimensions of the image. numberOfColorBands should be = 1.
[rows1 columns1 numberOfColorBands1] = size(grayImage)
% Resize the image to be 7383x481
grayImage = imresize(grayImage, [7383, 481]);
% Get the dimensions of the image. numberOfColorBands should be = 1.
[rows2 columns2 numberOfColorBands2] = size(grayImage)
figure;
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
set(gcf,'name','Demo by ImageAnalyst','numbertitle','off')
folder = pwd;
plotIndex = 1;
for i=1:23
% Extract out the small image.
row1 = (i-1)*321+1
row2 = row1 + 320
smallImage = grayImage(row1:row2, :);
% Display the small image.
subplot(5, 5, plotIndex);
imshow(smallImage);
caption = sprintf('Image #%d', plotIndex);
title(caption);
plotIndex = plotIndex + 1;
% Save the small image to disk.
baseFileName=sprintf('image%i.PNG',i);
fullFileName = fullfile(folder, baseFileName);
fprintf('Saving %s\n', fullFileName);
imwrite(smallImage, fullFileName);
end
  댓글 수: 3
Khalid
Khalid 2013년 5월 20일
First of all I would like to thanks you for this example code.
I have the same function, and I would like to do the following things: 1\My image have been divided to (4X12 blocks or parts), the total parts is 48 parts. I want to find the average value of each pixel (I mean each Block or part) which matrix should be (4X12).
Image Analyst
Image Analyst 2013년 5월 20일
You can do this with either example (indexing or blobkproc) that I provided here. Just change the numbers to be 4 and 12.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Image Analyst
Image Analyst 2012년 3월 30일
Dinyar, you're not accepting the output of blockproc into any variable, so how can you see the result? Here look at this demo of blockproc where I use two different ways of doing it, one with a separate function that returns a single value for each block that is processed (so the output image is smaller), and one with an anonymous function that returns a block the same size as the processing block (so the output image is the same size as the input image). I hope this demo helps you understand how blockproc works - I know it can be tricky and confusing. Simply copy, paste and run.
function blockproc_demo()
try
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
workspace; % Make sure the workspace panel is showing.
fontSize = 20;
% Change the current folder to the folder of this m-file.
if(~isdeployed)
cd(fileparts(which(mfilename)));
end
% Read in standard MATLAB demo image.
grayImage = imread('cameraman.tif');
[rows columns numberOfColorChannels] = size(grayImage);
% Display the original image.
subplot(2, 2, 1);
imshow(grayImage, []);
caption = sprintf('Original Image\n%d by %d pixels', ...
rows, columns);
title(caption, 'FontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'Position', get(0,'Screensize'));
set(gcf, 'name','Demo by ImageAnalyst', 'numbertitle','off')
%----------------- METHOD #1 -----------------------------------------------
% Block process the image.
windowSize = 3;
% Each 3x3 block will get replaced by one value.
% Output image will be smaller by a factor of windowSize.
myFilterHandle = @myFilter;
blockyImage = blockproc(grayImage,[windowSize windowSize], myFilterHandle);
[rowsP columnsP numberOfColorChannelsP] = size(blockyImage);
% Display the processed image.
% It is smaller, but the display routine imshow() replicates
% the image so that it looks bigger than it really is.
subplot(2, 2, 2);
imshow(blockyImage, []);
caption = sprintf('Image Processed in %d by %d Blocks\n%d by %d pixels\nCustom Box Filter', ...
windowSize, windowSize, rowsP, columnsP);
title(caption, 'FontSize', fontSize);
%----------------- METHOD #2 -----------------------------------------------
% Now let's do it an alternate way where we use an anonymous function.
% We'll take the standard deviation in the blocks.
windowSize = 8;
myFilterHandle2 = @(block_struct) ...
std2(block_struct.data) * ones(size(block_struct.data));
blockyImageSD = blockproc(grayImage, [windowSize windowSize], myFilterHandle2);
[rowsSD columnsSD numberOfColorChannelsSD] = size(blockyImageSD);
subplot(2, 2, 4);
imshow(blockyImageSD, []);
caption = sprintf('Image Processed in %d by %d Blocks\n%d by %d pixels\nAnonymous Standard Deviation Filter', ...
windowSize, windowSize, rowsSD, columnsSD);
title(caption, 'FontSize', fontSize);
% Note: the image size of blockyImageSD is 256x256, NOT smaller.
% That's because we're returning an 8x8 array instead of a scalar.
uiwait(msgbox('Done with demo'));
catch ME
errorMessage = sprintf('Error in blockproc_demo():\n\nError Message:\n%s', ME.message);
uiwait(warndlg(errorMessage));
end
return;
%==================================================================
% Takes one 3x3 block of image data and multiplies it
% element-by-element by the kernel and returns a single value.
function singleValue = myFilter(blockStruct)
try
% Assign default value.
% Will be used near sides of image (due to boundary effects),
% or in the case of errors, etc.
singleValue = 0;
% Create a 2D filter.
kernel = [0 0.2 0; 0.2 0.2 0.2; 0 0.2 0];
% kernel = ones(blockStruct.blockSize); % Box filter.
% Make sure filter size matches image block size.
if any(blockStruct.blockSize ~= size(kernel))
% If any of the dimensions don't match.
% You'll get here near the edges,
% if the image is not a multiple of the block size.
% warndlg('block size does not match kernel size');
return;
end
% Size matches if we get here, so we're okay.
% Extract our block out of the structure.
array3x3 = blockStruct.data;
% Do the filtering. Multiply by kernel and sum.
singleValue = sum(sum(double(array3x3) .* kernel));
catch ME
% Some kind of problem...
errorMessage = sprintf('Error in myFilter():\n\nError Message:\n%s', ME.message);
% uiwait(warndlg(errorMessage));
fprintf(1, '%s\n', errorMessage);
end
return;
  댓글 수: 2
Sandhiya Prakash
Sandhiya Prakash 2017년 3월 14일
Can I use blockproc for 3D image? Is that possible to use blockproc for image with .mha format?
Walter Roberson
Walter Roberson 2017년 3월 14일
"Can I use blockproc for 3D image?"
Yes. The entire third dimension is given for every block. You cannot use blockproc to divide the third dimension into pieces.
"Is that possible to use blockproc for image with .mha format?"
No. You would need to read the .mha file into an variable.

댓글을 달려면 로그인하십시오.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by