{"id":94,"date":"2006-11-17T14:29:54","date_gmt":"2006-11-17T19:29:54","guid":{"rendered":"https:\/\/blogs.mathworks.com\/steve\/?p=94"},"modified":"2019-10-22T16:33:51","modified_gmt":"2019-10-22T20:33:51","slug":"labeling-labeled-objects","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/steve\/2006\/11\/17\/labeling-labeled-objects\/","title":{"rendered":"Labeling labeled objects"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <p>A post in comp.soft-sys.matlab this week (see the third post in <a href=\"\">this thread<\/a>) asked how to display graphically the numerical labels associated with each labeled object. In this blog I'll show a couple\r\n      of ways to approach that task.\r\n   <\/p>\r\n   <p>First, let's back up a bit.  We're talking about labeling connected groups of pixels in binary images.  Here's an example,\r\n      starting with the grayscale image coins.png.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">I = imread(<span style=\"color: #A020F0\">'coins.png'<\/span>);\r\nimshow(I)<\/pre><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/steve\/94\/labeling_labeled_objects_01.png\"> <p>Threshold to form a binary image.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">bw = im2bw(I, graythresh(I));\r\nimshow(bw)<\/pre><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/steve\/94\/labeling_labeled_objects_02.png\"> <p>Fill in the holes.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">bw2 = imfill(bw, <span style=\"color: #A020F0\">'holes'<\/span>);\r\nimshow(bw2)<\/pre><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/steve\/94\/labeling_labeled_objects_03.png\"> <p>You can easily see that there are 10 objects in the image.  But to start doing geometric measurements, we have to be able\r\n      to identify which foreground pixels belong to which object.  That's what <a href=\"https:\/\/www.mathworks.com\/access\/helpdesk\/help\/toolbox\/images\/index.html?\/access\/helpdesk\/help\/toolbox\/images\/bwlabel.html&amp;\"><tt>bwlabel<\/tt><\/a> does.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">L = bwlabel(bw2);<\/pre><p><tt>L<\/tt> is a <i>label matrix<\/i>.  It's the same size as <tt>bw2<\/tt>.  It contains the value 0 in each location that's a background pixel.  It contains positive integer values in locations corresponding\r\n      to a labeled foreground object. For example, to see the eighth object, you just determine all the elements of <tt>L<\/tt> that equal 8:\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">imshow(L == 8)\r\ntitle(<span style=\"color: #A020F0\">'Object 8'<\/span>)<\/pre><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/steve\/94\/labeling_labeled_objects_04.png\"> <p>Getting back to the original question - How can we graphically display each object's label?  One way is to compute the centroid\r\n      of each object, and then superimpose text strings on top of the image at the centroid locations.  Here's one implementation:\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">s = regionprops(L, <span style=\"color: #A020F0\">'Centroid'<\/span>);\r\nimshow(bw2)\r\nhold <span style=\"color: #A020F0\">on<\/span>\r\n<span style=\"color: #0000FF\">for<\/span> k = 1:numel(s)\r\n    c = s(k).Centroid;\r\n    text(c(1), c(2), sprintf(<span style=\"color: #A020F0\">'%d'<\/span>, k), <span style=\"color: #0000FF\">...<\/span>\r\n        <span style=\"color: #A020F0\">'HorizontalAlignment'<\/span>, <span style=\"color: #A020F0\">'center'<\/span>, <span style=\"color: #0000FF\">...<\/span>\r\n        <span style=\"color: #A020F0\">'VerticalAlignment'<\/span>, <span style=\"color: #A020F0\">'middle'<\/span>);\r\n<span style=\"color: #0000FF\">end<\/span>\r\nhold <span style=\"color: #A020F0\">off<\/span><\/pre><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/steve\/94\/labeling_labeled_objects_05.png\"> <p>My second method is more interactive. It uses a fairly new MATLAB feature: Data cursors.\r\n   <\/p>\r\n   <p>If you haven't seen MATLAB data cursors before, here's a screen shot showing what happens when you click on a plot in data\r\n      cursor mode.\r\n   <\/p>\r\n   <p><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/steve\/94\/data_cursor_screenshot1.png\"> <\/p>\r\n   <p>Data cursors work for images, too:<\/p>\r\n   <p><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/steve\/94\/data_cursor_screenshot2.png\"> <\/p>\r\n   <p>With a modest bit of programming (see Customizing Data Cursor Text), you can customize the data cursor strings.  Here, we just want the object label to be displayed.  I wrote a little function\r\n      called <a href=\"https:\/\/blogs.mathworks.com\/images\/steve\/94\/display_label_matrix.m\"><tt>display_label_matrix<\/tt><\/a> that does just that.  It's just a dozen lines of code.  Here's what it looks like for the coins example:\r\n   <\/p>\r\n   <p><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/steve\/94\/data_cursor_screenshot3.png\"> <\/p>\r\n   <p>And here's the code:<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">type <span style=\"color: #A020F0\">display_label_matrix<\/span><\/pre><pre style=\"font-style:oblique\">\r\nfunction display_label_matrix(L)\r\n% display_label_matrix Display label matrix with custom data cursors\r\n% display_label_matrix(L) displays the label matrix L as colored objects on\r\n% a gray background.  It also installs a custom data cursor handler in the\r\n% figure.  In data cursor mode, clicking on an object displays a data\r\n% cursor containing the object's number.\r\n\r\n% Steve Eddins\r\n% Copyright 2006 The MathWorks, Inc.\r\n% $Revision: 1.1 $  $Date: 2006\/11\/17 19:11:30 $\r\n\r\nrgb = label2rgb(L, 'jet', [.7 .7 .7], 'shuffle');\r\nh = imshow(rgb);\r\n\r\n% Store the label matrix so that the custom data cursor function has access\r\n% to it.\r\nsetappdata(h, 'LabelMatrix', L);\r\n\r\n% Enable the figure data cursor mode, and use our own custom data cursor\r\n% strings.\r\ndcm = datacursormode(ancestor(h, 'figure'));\r\nset(dcm,'Enable','on', ...\r\n    'Updatefcn', @dataCursorText);\r\n\r\n%==========================================================================\r\nfunction output_text = dataCursorText(obj, event_obj)\r\n% Respond to a user click in data cursor mode by displaying the label\r\n% number of the pixel that was clicked on.\r\n\r\nh_image = get(event_obj, 'Target');\r\npos = get(event_obj, 'Position');\r\nL = getappdata(h_image, 'LabelMatrix');\r\nclicked_label = L(round(pos(2)), round(pos(1)));\r\noutput_text = sprintf('%d', clicked_label);\r\n%--------------------------------------------------------------------------\r\n\r\n\r\n\r\n<\/pre><p>Give it a try and let me know what you think.<\/p><script language=\"JavaScript\"> \r\n<!--\r\n    function grabCode_dc8f26c6f33a48f0beb4d9b7f035e316() {\r\n        \/\/ Remember the title so we can use it in the new page\r\n        title = document.title;\r\n\r\n        \/\/ Break up these strings so that their presence\r\n        \/\/ in the Javascript doesn't mess up the search for\r\n        \/\/ the MATLAB code.\r\n        t1='dc8f26c6f33a48f0beb4d9b7f035e316 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' dc8f26c6f33a48f0beb4d9b7f035e316';\r\n    \r\n        b=document.getElementsByTagName('body')[0];\r\n        i1=b.innerHTML.indexOf(t1)+t1.length;\r\n        i2=b.innerHTML.indexOf(t2);\r\n \r\n        code_string = b.innerHTML.substring(i1, i2);\r\n        code_string = code_string.replace(\/REPLACE_WITH_DASH_DASH\/g,'--');\r\n\r\n        \/\/ Use \/x3C\/g instead of the less-than character to avoid errors \r\n        \/\/ in the XML parser.\r\n        \/\/ Use '\\x26#60;' instead of '<' so that the XML parser\r\n        \/\/ doesn't go ahead and substitute the less-than character. \r\n        code_string = code_string.replace(\/\\x3C\/g, '\\x26#60;');\r\n\r\n        author = '';\r\n        copyright = '';\r\n\r\n        w = window.open();\r\n        d = w.document;\r\n        d.write('<pre>\\n');\r\n        d.write(code_string);\r\n\r\n        \/\/ Add author and copyright lines at the bottom if specified.\r\n        if ((author.length > 0) || (copyright.length > 0)) {\r\n            d.writeln('');\r\n            d.writeln('%%');\r\n            if (author.length > 0) {\r\n                d.writeln('% _' + author + '_');\r\n            }\r\n            if (copyright.length > 0) {\r\n                d.writeln('% _' + copyright + '_');\r\n            }\r\n        }\r\n\r\n        d.write('<\/pre>\\n');\r\n      \r\n      d.title = title + ' (MATLAB code)';\r\n      d.close();\r\n      }   \r\n-->\r\n      <\/script>\r\n<noscript>\r\n<em>A JavaScript-enabled browser is required to use the \"Get the MATLAB code\" link.<\/em>\r\n<\/noscript>\r\n<p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><br><a href=\"javascript:grabCode_dc8f26c6f33a48f0beb4d9b7f035e316()\"><span style=\"font-size: x-small;        font-style: italic;\">Get \r\n            the MATLAB code<\/span><\/a><br><br>\r\n      Published with MATLAB&reg; 7.3<br><\/p>\r\n<\/div>\r\n<!--\r\ndc8f26c6f33a48f0beb4d9b7f035e316 ##### SOURCE BEGIN #####\r\n%% Labeling labeled images\r\n% A post in comp.soft-sys.matlab this week (see the third post in \r\n% < this \r\n% thread>) asked how to display graphically the numerical labels associated\r\n% with each labeled object. In this blog I'll show a couple of ways to\r\n% approach that task.\r\n%\r\n% First, let's back up a bit.  We're talking about labeling connected groups\r\n% of pixels in binary objects.  Here's an example, starting with the\r\n% grayscale image coins.png.\r\n\r\nI = imread('coins.png');\r\nimshow(I)\r\n\r\n%%\r\n% Threshold to form a binary image.\r\n\r\nbw = im2bw(I, graythresh(I));\r\nimshow(bw)\r\n\r\n%%\r\n% Fill in the holes.\r\n\r\nbw2 = imfill(bw, 'holes');\r\nimshow(bw2)\r\n\r\n%%\r\n% You can easily see that there are 10 objects in the image.  But to start\r\n% doing geometric measurements, we have to be able to identify which\r\n% foreground pixels belong to which object.  That's what \r\n% <https:\/\/www.mathworks.com\/access\/helpdesk\/help\/toolbox\/images\/index.html?\/access\/helpdesk\/help\/toolbox\/images\/bwlabel.html& |bwlabel|> \r\n% does.\r\n\r\nL = bwlabel(bw2);\r\n\r\n%%\r\n% |L| is a _label matrix_.  It's the same size as |bw2|.  It contains the\r\n% value 0 in each location that's a background pixel.  It contains positive\r\n% integer values in locations corresponding to a labeled foreground object.\r\n% For example, to see the eighth object, you just determine all the\r\n% elements of |L| that equal 8:\r\n\r\nimshow(L == 8)\r\ntitle('Object 8')\r\n\r\n%%\r\n% Getting back to the original question - How can we graphically display\r\n% each object's label?  One way is to compute the centroid of each object,\r\n% and then superimpose text strings on top of the image at the centroid\r\n% locations.  Here's one implementation:\r\n\r\ns = regionprops(L, 'Centroid');\r\nimshow(bw2)\r\nhold on\r\nfor k = 1:numel(s)\r\n    c = s(k).Centroid;\r\n    text(c(1), c(2), sprintf('%d', k), ...\r\n        'HorizontalAlignment', 'center', ...\r\n        'VerticalAlignment', 'middle');\r\nend\r\nhold off\r\n\r\n%%\r\n% My second method is more interactive. It uses a fairly new MATLAB\r\n% feature:  <https:\/\/www.mathworks.com\/access\/helpdesk\/help\/techdoc\/creating_plots\/f4-44221.html \r\n% Data cursors>.\r\n%\r\n% If you haven't seen MATLAB data cursors before, here's a screen shot\r\n% showing what happens when you click on a plot in data cursor mode.\r\n%\r\n% <<https:\/\/blogs.mathworks.com\/images\/steve\/94\/data_cursor_screenshot1.png>>\r\n%\r\n% Data cursors work for images, too:\r\n%\r\n% <<https:\/\/blogs.mathworks.com\/images\/steve\/94\/data_cursor_screenshot2.png>>\r\n%\r\n% With a modest bit of programming (see <https:\/\/www.mathworks.com\/access\/helpdesk\/help\/techdoc\/creating_plots\/f4-44236.html\r\n% Customizing Data Cursor Text>), you can customize the\r\n% data cursor strings.  Here, we just want the object label to be\r\n% displayed.  I wrote a little function called |display_label_matrix| that\r\n% does just that.  It's just a dozen lines of code.  Here's what it looks\r\n% like for the coins example:\r\n%\r\n% <<https:\/\/blogs.mathworks.com\/images\/steve\/94\/data_cursor_screenshot3.png>>\r\n%\r\n% And here's the code:\r\n\r\ntype display_label_matrix\r\n\r\n%%\r\n% Give it a try and let me know what you think.\r\n\r\n##### SOURCE END ##### dc8f26c6f33a48f0beb4d9b7f035e316\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n   A post in comp.soft-sys.matlab this week (see the third post in this thread) asked how to display graphically the numerical labels associated with each labeled object. In this blog I'll show a... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/steve\/2006\/11\/17\/labeling-labeled-objects\/\">read more >><\/a><\/p>","protected":false},"author":42,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[1],"tags":[272,166,266,268,90,84,136,76,36,152,162,168,188,264,270,78,52],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/steve\/wp-json\/wp\/v2\/posts\/94"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/steve\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/steve\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/steve\/wp-json\/wp\/v2\/users\/42"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/steve\/wp-json\/wp\/v2\/comments?post=94"}],"version-history":[{"count":1,"href":"https:\/\/blogs.mathworks.com\/steve\/wp-json\/wp\/v2\/posts\/94\/revisions"}],"predecessor-version":[{"id":2206,"href":"https:\/\/blogs.mathworks.com\/steve\/wp-json\/wp\/v2\/posts\/94\/revisions\/2206"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/steve\/wp-json\/wp\/v2\/media?parent=94"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/steve\/wp-json\/wp\/v2\/categories?post=94"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/steve\/wp-json\/wp\/v2\/tags?post=94"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}