Computer vision: Binary and inverse thresholds

A threshold is the fastest way to separate objects from the background.

What to build

A program that thresholds an image and counts the foreground pixels.

Requirements

  • Mode binary: # where the value is greater than T, . otherwise. Mode inverse: # where the value is at most T.
  • Print the mask, then foreground N of M pixels.

Input

Line 1: H, W, T and the mode. Then H rows of W values.

Output

H mask lines and the count line.

Constraints

1 ≤ H, W ≤ 80; 0 ≤ T ≤ 255.

Example

Input:

2 3 100 binary
50 150 100
101 0 255

Output:

.#.
#.#
foreground 3 of 6 pixels

Why it works

Comparing every pixel with the same level splits the image into two classes in one pass; the inverse mode simply swaps which class is the foreground.

Examples

Example 1 · Input
2 3 100 binary
50 150 100
101 0 255
Expected output
.#.
#.#
foreground 3 of 6 pixels
Example 2 · Input
2 2 100 inverse
50 150
100 200
Expected output
#.
#.
foreground 2 of 4 pixels

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

For `binary`, a pixel is foreground when v > T; for `inverse`, when v ≤ T.

Hint 2

Count the foreground pixels as you build each line.

Solution

Show one correct solution (try it yourself first)
h, w, t, mode = input().split()
h, w, t = int(h), int(w), int(t)
count = 0
for _ in range(h):
    line = ""
    for v in map(int, input().split()):
        on = v > t if mode == "binary" else v <= t
        line += "#" if on else "."
        count += on
    print(line)
print(f"foreground {count} of {h * w} pixels")

Lesson: Thresholding and Otsu's method →