How to blur text in image?

18 views (last 30 days)
Dominik Mattioli
Dominik Mattioli on 10 Jun 2021
Commented: Image Analyst on 5 Jan 2022 at 17:13
I'd like to blur only the text found in some images (potentially-sensitive medical information). I'm struggling to remember how to convert bounding boxes into matrix indices, or whether there is a function that does the following.
img = imread('businessCard.png');
imgOCR = ocr( img )
for idx = 1:numel( imgOCR.Words )
bbox = imgOCR.WordBoundingBoxes( idx, : )
subImg = imcrop( img, bbox )
K = medfilt2( subImg )
%%% How to insert K back into img? something like:
% newImg = iminsert( img, bbox, K );
end

Accepted Answer

Image Analyst
Image Analyst on 10 Jun 2021
Somehow you need to create a mask defining where the text is. Once you got that, blur the entire image, and blur the mask also. Then get the new larger mask and assign the blurred image to the original image in the blurred mask. In short, something like
windowSize = 15; % Whatever.
kernel = ones(windowSize, windowSize) / windowSize^2;
% Blur the mask and the image.
blurredImage = conv2(double(grayimage), kernel, 'same');
blurredMask = conv2(double(mask), kernel, 'same');
newMask = blurredMask > 0; % Mask is now bigger since it got blurred.
% Replace original pixels with blurred pixels.
grayImage(newMask) = blurredImage(newMask);
It would be easier to simply erase the image in the mask than to blur the text and replace it.
grayImage(mask) = 0;
  4 Comments
Image Analyst
Image Analyst on 5 Jan 2022 at 17:13
@Johnal Khow I'm not sure if you can do it in a single call to poly2mask. For simple things like bounding boxes, I'd just have a single binary image and loop over all bounding boxes, writing "true" to the bounding box. Like this:
props = regionprops(mask, 'BoundingBox');
allBB = vertcat(props.BoundingBox);
mask = false(rows, columns);
for k = 1 : length(props)
row1 = ceil(allBB(k, 2));
row2 = floor(allBB(k, 2) + allBB(k, 4));
col1 = ceil(allBB(k, 1));
col2 = floor(allBB(k, 1) + allBB(k, 3));
mask(row1:row2, col1:col2) = true;
end

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by