{"id":206,"date":"2008-04-14T09:50:14","date_gmt":"2008-04-14T13:50:14","guid":{"rendered":"https:\/\/blogs.mathworks.com\/steve\/2008\/04\/14\/relabeling-a-label-matrix\/"},"modified":"2019-10-28T09:28:38","modified_gmt":"2019-10-28T13:28:38","slug":"relabeling-a-label-matrix","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/steve\/2008\/04\/14\/relabeling-a-label-matrix\/","title":{"rendered":"Relabeling a label matrix"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <p>The three most common questions I've been hearing about <tt>bwlabel<\/tt>, which is used for labeling connected components in a binary image, are about\r\n   <\/p>\r\n   <div>\r\n      <ul>\r\n         <li>Search order<\/li>\r\n         <li>Relabeling (renumbering the label matrix)<\/li>\r\n         <li>Correspondence between labels in two different images<\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <p>Today I'll tackle relabeling.<\/p>\r\n   <p>In my <a href=\"https:\/\/blogs.mathworks.com\/steve\/2008\/03\/25\/bwlabel-search-order\/\">previous post on search order<\/a>, I showed how to postprocess the labeled objects to modify their order according to various criteria.  Now I'll take that\r\n      a step further and use the sorted output from regionprops to renumber the labels in the label matrix.\r\n   <\/p>\r\n   <p>Blog reader <a href=\"https:\/\/blogs.mathworks.com\/steve\/2008\/03\/25\/bwlabel-search-order\/#comment-20522\">Trung<\/a> wanted to know if we could sort lexicographically by centroid, so I'll do that here.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">url = <span style=\"color: #A020F0\">'https:\/\/blogs.mathworks.com\/images\/steve\/186\/scanned_page.png'<\/span>;\r\nbw = imread(url);\r\nbw = ~bw(1107:1194, 17:135);\r\nimshow(bw, <span style=\"color: #A020F0\">'InitialMagnification'<\/span>, <span style=\"color: #A020F0\">'fit'<\/span>)<\/pre><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/steve\/2008\/bwlabel_relabeling_01.png\"> <p>Here's a false-color view of the label matrix using <tt>label2rgb<\/tt>:\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">L = bwlabel(bw);\r\nrgb = label2rgb(L, <span style=\"color: #A020F0\">'jet'<\/span>, [.95 .95 .95], <span style=\"color: #A020F0\">'shuffle'<\/span>);\r\nimshow(rgb, <span style=\"color: #A020F0\">'InitialMagnification'<\/span>, <span style=\"color: #A020F0\">'fit'<\/span>)<\/pre><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/steve\/2008\/bwlabel_relabeling_02.png\"> <p>Now let's use <tt>regionprops<\/tt> to get the centroids for each object.  To facilitate the relabeling step, I'll get the <tt>'PixelIdxList'<\/tt> for each object.\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>, <span style=\"color: #A020F0\">'PixelIdxList'<\/span>});<\/pre><p>Next, sort lexicographically by the centroids, sorting first by the vertical coordinate.<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">centroids = cat(1, s.Centroid);\r\n[sorted_centroids, sort_order] = sortrows(fliplr(centroids));\r\ns2 = s(sort_order);<\/pre><p>To visualize the sorted object order, we can display the object numbers on top of the objects like this:<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\"><span style=\"color: #228B22\">% First, make an image with a light gray background instead<\/span>\r\n<span style=\"color: #228B22\">% of a black background, so that the numbers will be visible<\/span>\r\n<span style=\"color: #228B22\">% on top of it.<\/span>\r\nI = im2uint8(bw);\r\nI(~bw) = 200;\r\nI(bw) = 240;\r\nimshow(I, <span style=\"color: #A020F0\">'InitialMagnification'<\/span>, <span style=\"color: #A020F0\">'fit'<\/span>)\r\n\r\n<span style=\"color: #228B22\">% Now plot the number of each sorted object at the corresponding<\/span>\r\n<span style=\"color: #228B22\">% centroid:<\/span>\r\nhold <span style=\"color: #A020F0\">on<\/span>\r\n<span style=\"color: #0000FF\">for<\/span> k = 1:numel(s2)\r\n   centroid = s2(k).Centroid;\r\n   text(centroid(1), centroid(2), sprintf(<span style=\"color: #A020F0\">'%d'<\/span>, k));\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\/2008\/bwlabel_relabeling_03.png\"> <p>We sorted the output of <tt>regionprops<\/tt>, but we haven't touched the label matrix itself.  We can relabel it according to the sort order by using linear indexing\r\n      and the <tt>PixelIdxList<\/tt> of each object.  An object's <tt>PixelIdxList<\/tt> is a vector of linear indices for the pixels belonging to the object.  Here's the relabeling loop:\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\"><span style=\"color: #0000FF\">for<\/span> k = 1:numel(s2)\r\n   kth_object_idx_list = s2(k).PixelIdxList;\r\n   L(kth_object_idx_list) = k;\r\n<span style=\"color: #0000FF\">end<\/span><\/pre><p>In MATLAB 7.6 (R2008a), the <tt>publish<\/tt> feature lets you capture multiple graphics from within a loop.  I'll use that new capability to show the location of the\r\n      first few relabeled objects in <tt>L<\/tt>.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\"><span style=\"color: #0000FF\">for<\/span> k = 1:5<\/pre><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">   imshow(L == k)<\/pre><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/steve\/2008\/bwlabel_relabeling_04.png\"> <img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/steve\/2008\/bwlabel_relabeling_05.png\"> <img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/steve\/2008\/bwlabel_relabeling_06.png\"> <img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/steve\/2008\/bwlabel_relabeling_07.png\"> <img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/steve\/2008\/bwlabel_relabeling_08.png\"> <pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\"><span style=\"color: #0000FF\">end<\/span><\/pre><p>Soon I'll write another post that shows how how to match up labels in objects that overlap between two images.<\/p><script language=\"JavaScript\">\r\n<!--\r\n\r\n    function grabCode_98d2aec8b96849a8ad9d5f6ccc5577d4() {\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='98d2aec8b96849a8ad9d5f6ccc5577d4 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 98d2aec8b96849a8ad9d5f6ccc5577d4';\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 = 'Steve Eddins';\r\n        copyright = 'Copyright 2008 The MathWorks, Inc.';\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-->\r\n<\/script><p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><br><a href=\"javascript:grabCode_98d2aec8b96849a8ad9d5f6ccc5577d4()\"><span style=\"font-size: x-small;        font-style: italic;\">Get \r\n            the MATLAB code \r\n            <noscript>(requires JavaScript)<\/noscript><\/span><\/a><br><br>\r\n      Published with MATLAB&reg; 7.6<br><\/p>\r\n<\/div>\r\n<!--\r\n98d2aec8b96849a8ad9d5f6ccc5577d4 ##### SOURCE BEGIN #####\r\n%%\r\n% The three most common questions I've been hearing about \r\n% <https:\/\/www.mathworks.com\/help\/images\/index.htmlbwlabel.html \r\n% |bwlabel|>, which is\r\n% used for labeling connected components in a binary image, are about\r\n%\r\n% * Search order\r\n% * Relabeling (renumbering the label matrix)\r\n% * Correspondence between labels in two different images\r\n%\r\n% Today I'll tackle relabeling.\r\n%\r\n% In my \r\n% <https:\/\/blogs.mathworks.com\/steve\/2008\/03\/25\/bwlabel-search-order\/ \r\n% previous post on search order>, I showed how to postprocess the labeled\r\n% objects to modify their order according to various criteria.  Now I'll take\r\n% that a step further and use the sorted output from regionprops to renumber the\r\n% labels in the label matrix.\r\n%\r\n% Blog reader\r\n% <https:\/\/blogs.mathworks.com\/steve\/2008\/03\/25\/bwlabel-search-order\/#comment-20522 \r\n% Trung> wanted to know if we could sort lexicographically by centroid, so I'll\r\n% do that here.\r\n\r\nurl = 'https:\/\/blogs.mathworks.com\/images\/steve\/186\/scanned_page.png';\r\nbw = imread(url);\r\nbw = ~bw(1107:1194, 17:135);\r\nimshow(bw, 'InitialMagnification', 'fit')\r\n\r\n%%\r\n% Here's a false-color view of the label matrix using \r\n% <https:\/\/www.mathworks.com\/help\/images\/index.htmllabel2rgb.html \r\n% |label2rgb|>:\r\n\r\nL = bwlabel(bw);\r\nrgb = label2rgb(L, 'jet', [.95 .95 .95], 'shuffle');\r\nimshow(rgb, 'InitialMagnification', 'fit')\r\n\r\n%%\r\n% Now let's use |regionprops| to get the centroids for each object.  To\r\n% facilitate the relabeling step, I'll get the |'PixelIdxList'| for each object.\r\n\r\ns = regionprops(L, {'Centroid', 'PixelIdxList'});\r\n\r\n%%\r\n% Next, sort lexicographically by the centroids, sorting first by the vertical\r\n% coordinate.\r\n\r\ncentroids = cat(1, s.Centroid);\r\n[sorted_centroids, sort_order] = sortrows(fliplr(centroids));\r\ns2 = s(sort_order);\r\n\r\n%%\r\n% To visualize the sorted object order, we can display the object numbers on top\r\n% of the objects like this:\r\n\r\n% First, make an image with a light gray background instead \r\n% of a black background, so that the numbers will be visible \r\n% on top of it.\r\nI = im2uint8(bw);\r\nI(~bw) = 200;\r\nI(bw) = 240;\r\nimshow(I, 'InitialMagnification', 'fit')\r\n\r\n% Now plot the number of each sorted object at the corresponding \r\n% centroid:\r\nhold on\r\nfor k = 1:numel(s2)\r\n   centroid = s2(k).Centroid;\r\n   text(centroid(1), centroid(2), sprintf('%d', k));\r\nend\r\nhold off\r\n\r\n%%\r\n% We sorted the output of |regionprops|, but we haven't touched the label matrix\r\n% itself.  We can relabel it according to the sort order by using linear\r\n% indexing and the |PixelIdxList| of each object.  An object's |PixelIdxList| is \r\n% a vector of linear indices for the pixels belonging to the object.  Here's the\r\n% relabeling loop:\r\n\r\nfor k = 1:numel(s2)\r\n   kth_object_idx_list = s2(k).PixelIdxList;\r\n   L(kth_object_idx_list) = k;\r\nend\r\n\r\n%%\r\n% In MATLAB 7.6 (R2008a), the \r\n% <https:\/\/www.mathworks.com\/access\/helpdesk\/help\/techdoc\/matlab_env\/f6-22451.html \r\n% |publish|> feature lets you capture multiple \r\n% graphics from within a loop.  I'll use that new capability to show the\r\n% location of the first few relabeled objects in |L|.\r\n\r\nfor k = 1:5\r\n   %%\r\n   imshow(L == k)\r\nend\r\n\r\n%%\r\n% Soon I'll write another post that shows how how to match up labels in objects\r\n% that overlap between two images.\r\n##### SOURCE END ##### 98d2aec8b96849a8ad9d5f6ccc5577d4\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n   The three most common questions I've been hearing about bwlabel, which is used for labeling connected components in a binary image, are about\r\n   \r\n   \r\n      \r\n         Search order\r\n ... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/steve\/2008\/04\/14\/relabeling-a-label-matrix\/\">read more >><\/a><\/p>","protected":false},"author":42,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[16],"tags":[166,46,90,452,76,36,152,162,168,486,78],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/steve\/wp-json\/wp\/v2\/posts\/206"}],"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=206"}],"version-history":[{"count":2,"href":"https:\/\/blogs.mathworks.com\/steve\/wp-json\/wp\/v2\/posts\/206\/revisions"}],"predecessor-version":[{"id":2224,"href":"https:\/\/blogs.mathworks.com\/steve\/wp-json\/wp\/v2\/posts\/206\/revisions\/2224"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/steve\/wp-json\/wp\/v2\/media?parent=206"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/steve\/wp-json\/wp\/v2\/categories?post=206"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/steve\/wp-json\/wp\/v2\/tags?post=206"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}