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
Removing Horizontal Lines in image (OpenCV, Python, Matplotlib)
Removing horizontal lines from images is useful for preprocessing scanned documents or cleaning up images with unwanted line artifacts. We'll use OpenCV's morphological operations to detect and remove these lines while preserving the important content.
Understanding the Process
The horizontal line removal process involves several key steps ?
- Convert the image to grayscale and apply thresholding
- Use horizontal morphological kernels to detect line structures
- Find contours of the detected lines
- Remove the lines by drawing over them
- Apply repair operations to restore nearby content
Complete Implementation
Here's a complete example that demonstrates horizontal line removal ?
import cv2
import numpy as np
# Create a sample image with horizontal lines for demonstration
def create_sample_image():
img = np.ones((200, 300, 3), dtype=np.uint8) * 255
# Add some text-like rectangles
cv2.rectangle(img, (50, 50), (120, 70), (0, 0, 0), -1)
cv2.rectangle(img, (150, 50), (250, 70), (0, 0, 0), -1)
cv2.rectangle(img, (50, 120), (180, 140), (0, 0, 0), -1)
# Add horizontal lines
cv2.line(img, (0, 90), (300, 90), (0, 0, 0), 2)
cv2.line(img, (0, 160), (300, 160), (0, 0, 0), 2)
return img
# Load or create image
image = create_sample_image()
original = image.copy()
# Step 1: Convert to grayscale and apply threshold
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
# Step 2: Create horizontal kernel and detect lines
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (25, 1))
detected_lines = cv2.morphologyEx(thresh, cv2.MORPH_OPEN,
horizontal_kernel, iterations=2)
# Step 3: Find contours of detected lines
cnts = cv2.findContours(detected_lines, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
# Step 4: Remove lines by drawing white over them
for c in cnts:
cv2.drawContours(image, [c], -1, (255, 255, 255), 2)
# Step 5: Repair nearby content
repair_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 6))
result = 255 - cv2.morphologyEx(255 - image, cv2.MORPH_CLOSE,
repair_kernel, iterations=1)
print("Horizontal line removal completed successfully!")
Key Parameters Explained
| Parameter | Purpose | Typical Values |
|---|---|---|
| Horizontal Kernel Size | Detects horizontal structures | (25, 1) to (40, 1) |
| MORPH_OPEN Iterations | Refines line detection | 1 to 3 |
| Repair Kernel Size | Fixes nearby content | (1, 4) to (1, 8) |
Working with Real Images
For actual image files, replace the sample creation with file loading ?
import cv2
# Load your image
image = cv2.imread('your_image.png')
# Check if image loaded successfully
if image is None:
print("Error: Could not load image")
else:
# Apply the same horizontal line removal process
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# ... rest of the code remains the same
Adjusting for Different Line Thickness
For thicker or thinner lines, adjust the kernel sizes accordingly ?
# For thinner lines (1-2 pixels) horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (15, 1)) # For thicker lines (3-5 pixels) horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (35, 1)) # Adjust repair kernel based on content density repair_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 4)) # Less repair repair_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 8)) # More repair
Conclusion
Horizontal line removal using OpenCV involves morphological operations to detect and eliminate line structures while preserving important content. Adjust kernel sizes based on your specific line thickness and image characteristics for optimal results.
