DIP+CV · Programming Exercise

EP03_05 — 🔲 Binary AND Mask Application

3.12.5 EP03_05 🔲 Binary AND Mask Application

In industrial computer vision inspection systems, it is necessary to isolate regions of interest (ROI) in part images to verify manufacturing defects. The bitwise AND operation with a binary mask is the fundamental mechanism for precisely cropping the inspection area, zeroing all pixels outside it.

See Figure 3.30 for a simulation of this exercise.

3.12.5.1 📋 Implementation Guidelines

  1. Dimensions: Read the integers \(L\) (rows) and \(C\) (columns).
  2. Data: Read the pixel matrix \(f\) (values \(\in [0, 255]\)).
  3. Mask: Read the binary matrix \(m\) (values: only 0 or 255).
  4. Mapping: For each pixel \((i,j)\), apply the bitwise AND:

\[ g(i,j) = f(i,j) \;\text{AND}\; m(i,j) \]

where \(255 =\) 11111111 and \(0 =\) 00000000 in binary.

  1. Output: Display the resulting \(L \times C\) matrix.

3.12.5.2 📌 Computational Constraints

  • AND with 255: \(p \; \text{AND} \; 255 = p\) (all bits preserved).
  • AND with 0: \(p \; \text{AND} \; 0 = 0\) (all bits zeroed).
  • Mask: The only possible values in the mask are 0 and 255.
  • Implementation: In Python, bitwise AND between integers uses the & operator.

3.12.5.3 🧠 Theoretical Foundation

Pixel \(f\) Mask \(m\) Result \(f\) AND \(m\)
any \(v\) 255 (11111111) \(v\) (preserved)
any \(v\) 0 (00000000) 0 (zeroed)

3.12.5.4 📦 Input and Output Specification (VPL)

Input:

  • Line 1: Integer \(L\).
  • Line 2: Integer \(C\).
  • Following lines: Elements of \(f\) (\(L\) rows).
  • Following lines: Elements of \(m\) (\(L\) rows with values 0 or 255).

Output:

  • Resulting \(L \times C\) matrix.

3.12.5.5 📌 Examples

Input Output Observation
2
3
100 150 200
50 80 120
255 255 0
0 255 255
100 150 0
0 80 120
Mask selects region
1
4
10 20 30 40
255 0 255 0
10 0 30 0 Alternating preserved/zeroed
⬛ Simulator EP03_05: Binary AND Mask g = f AND m

Click on the cells of the Mask m to toggle between pass-through (255) and blocking (0), applying the logical operation pixel by pixel.

Image f (0–255)
Mask m (Click to Toggle)
Result g = f AND m
—
—preserved
—zeroed
—visible
Legend:
255
Pass-through (preserved)
0
Blocking (zeroed)
g(i,j) = f(i,j) & m(i,j)
Figure 3.30: EP03_05 Simulator: Binary AND Mask Application
%%writefile EP03_05.cpp
// your solution
Overwriting EP03_05.cpp
TestSuite("EP03_05.cpp").run()
✔️ EP03_05.cases already exists in casos/
📋 5 case(s) loaded from casos/EP03_05.cases

🔍 Testing C++: EP03_05.cpp
⚠️ EP03_05.cpp: Empty file (fewer than 3 lines). Tests skipped.