MATLAB: Eliminating Groups of Connected Pixels.

bwareaopenImage Processing Toolbox

I would like to be able to look at the matrices of an image and convert certain connected pixel groups from 1’s to 0’s. I would like to be able look at each individual rows and columns and convert groups or individual pixel that are smaller than a defined amount of pixels. I have used the bwareaopen function to eliminate pixel groups that are smaller than a defined amount. But I cannot determine how to use this concept for individual rows or columns.
For example, I would like to eliminate the square in the first image below. . .
. .

Best Answer

First of all, you shouldn't use highly compressed jepg images for image analysis or else you get bad artifacts like you're seeing.
The "square" is the outermost object and will have label 1. So label everything and remove it. Something like this (untested off the top of my head);
[labeledImage, numberOfRegions] = bwlabel(binaryImage);
% Binarize the labeled image to get back to a binary image again.
binaryImage = labeledImage > 1; % Keep all except region #1.