Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Flipping an Image in Python
Flipping an image in Python involves two operations: horizontally reversing each row and then inverting the binary values (0 becomes 1, 1 becomes 0). This is commonly used in image processing and computer vision applications.
Given a binary matrix representing an image, we need to flip it horizontally and then invert all values ?
Input and Expected Output
For the input matrix:
| 1 | 1 | 0 |
| 1 | 0 | 1 |
| 0 | 0 | 0 |
The expected output after flipping and inverting:
| 1 | 0 | 0 |
| 0 | 1 | 0 |
| 1 | 1 | 1 |
Algorithm Steps
- Create an empty result list
- For each row in the matrix:
- Reverse the row using slicing
[::-1] - Invert each element (0 ? 1, 1 ? 0)
- Add the processed row to result
- Reverse the row using slicing
- Return the result matrix
Basic Implementation
Here's the step-by-step implementation of the flip and invert operation ?
def flipAndInvertImage(matrix):
result = []
for row in matrix:
# Step 1: Reverse the row
reversed_row = row[::-1]
# Step 2: Invert each element
for j in range(len(reversed_row)):
if reversed_row[j] == 1:
reversed_row[j] = 0
else:
reversed_row[j] = 1
result.append(reversed_row)
return result
# Test the function
matrix = [[1,1,0], [1,0,1], [0,0,0]]
result = flipAndInvertImage(matrix)
print(result)
[[1, 0, 0], [0, 1, 0], [1, 1, 1]]
Optimized Implementation
We can make this more concise using list comprehension and the XOR operator ?
def flipAndInvertImage(matrix):
# Flip horizontally and invert in one step
return [[1 - cell for cell in row[::-1]] for row in matrix]
# Alternative using XOR operator
def flipAndInvertImageXOR(matrix):
return [[cell ^ 1 for cell in row[::-1]] for row in matrix]
# Test both approaches
matrix = [[1,1,0], [1,0,1], [0,0,0]]
result1 = flipAndInvertImage(matrix)
result2 = flipAndInvertImageXOR(matrix)
print("Using subtraction:", result1)
print("Using XOR:", result2)
Using subtraction: [[1, 0, 0], [0, 1, 0], [1, 1, 1]] Using XOR: [[1, 0, 0], [0, 1, 0], [1, 1, 1]]
How It Works
The algorithm works in two phases:
-
Horizontal Flip:
row[::-1]reverses each row -
Inversion:
1 - cellorcell ^ 1inverts binary values
For the first row [1,1,0]:
- After flip:
[0,1,1] - After invert:
[1,0,0]
Comparison of Methods
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Loop-based | O(m × n) | O(m × n) | High |
| List comprehension | O(m × n) | O(m × n) | Medium |
| XOR approach | O(m × n) | O(m × n) | Medium |
Conclusion
Image flipping and inversion can be efficiently implemented using Python's slicing and list comprehension. The XOR operator provides a clean way to invert binary values, while 1 - cell is more readable for beginners.
