How can I count all pixel values that are not black(0)?

10 ビュー (過去 30 日間)
Serena Tenhumberg
Serena Tenhumberg 2018 年 7 月 27 日
編集済み: Ben Frankel 2018 年 7 月 27 日
I have a binary image with cropped regions that are black, and I need a count of all the pixels that are not cropped?

回答 (2 件)

Ben Frankel
Ben Frankel 2018 年 7 月 27 日
編集済み: Ben Frankel 2018 年 7 月 27 日
If the image is stored as a binary matrix M, you can use this:
count = sum(M(:) ~= 0);
For very large images, this runs much faster than sum(M(:)) and nnz(M), and it works for grayscale images as well.
EDIT: Thanks to Stephen for pointing out my mistake.

Stephen23
Stephen23 2018 年 7 月 27 日
編集済み: Stephen23 2018 年 7 月 27 日
Where I is your image:
nnz(I)
Note that this is robust to using different values for encoding the non-zero value in the binary image, e.g. sometimes binary images are encoded using 0 and 255 with uint8.
  1 件のコメント
Ben Frankel
Ben Frankel 2018 年 7 月 27 日
If the image is large enough or the count is calculated often enough, sum will be faster because it doesn't require a comparison to 0.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeRead, Write, and Modify Image についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by