Thư viện xử lý ảnh thông minh với hỗ trợ GPU tự động
Project description
MagicImg - Thư viện xử lý ảnh thông minh
MagicImg là thư viện Python mạnh mẽ cho xử lý và tiền xử lý ảnh, được tối ưu cho OCR và computer vision với hỗ trợ GPU tự động.
🚀 Tính năng mới trong v1.0.6
- ✅ Sửa lỗi API consistency: Tất cả wrapper functions giờ đây trả về format nhất quán
- ✅ Tối ưu type annotations: Cải thiện type hints cho tất cả functions
- ✅ Enhanced error handling: Xử lý lỗi tốt hơn trong các API functions
- ✅ Preserve color option: Tùy chọn giữ nguyên màu sắc ảnh gốc
- ✅ API stability: Không còn lỗi unpack ProcessingResult objects
📦 Cài đặt
Cài đặt cơ bản
pip install magicimg
Cài đặt với GPU support
pip install magicimg[gpu]
# hoặc
pip install magicimg torch torchvision
Cài đặt Tesseract OCR
Windows
# Sử dụng winget
winget install UB-Mannheim.TesseractOCR
# Thêm vào PATH
set PATH=%PATH%;C:\Program Files\Tesseract-OCR
Ubuntu/Debian
sudo apt-get update
sudo apt-get install tesseract-ocr tesseract-ocr-vie
macOS
brew install tesseract
🎯 Sử dụng nhanh
Basic Usage
import magicimg
# Xử lý ảnh cơ bản với preserve color
result = magicimg.process_image("input.jpg", "output.jpg", preserve_color=True)
print(f"Success: {result.success}")
print(f"Processing steps: {result.processing_steps}")
# Kiểm tra chất lượng ảnh
is_good, quality_info, enhanced = magicimg.check_image_quality("input.jpg")
print(f"Quality score: {quality_info['quality_score']}")
# Tăng cường ảnh
enhanced = magicimg.enhance_image("input.jpg", "enhanced.jpg")
# Preprocessing cho OCR (tối ưu cho text recognition)
result = magicimg.preprocess_for_ocr("input.jpg", "output.jpg", preserve_color=False)
API Mode (cho Google, Anthropic, Local API)
import magicimg
# Preprocessing cho Google Vision API
success, info, output_path = magicimg.preprocess_image_for_api(
"input.jpg",
provider="google",
output_dir="./output/",
min_quality_score=0.3
)
print(f"Success: {success}")
print(f"Output: {output_path}")
print(f"Processing steps: {info['processing_steps']}")
📚 API Reference
Core Functions
process_image(image_path, output_path=None, auto_rotate=True, preserve_color=True)
Xử lý ảnh hoàn chỉnh với tất cả các bước tối ưu.
Parameters:
image_path(str | np.ndarray): Đường dẫn ảnh hoặc numpy arrayoutput_path(str, optional): Đường dẫn lưu kết quảauto_rotate(bool): Tự động xoay ảnh (default: True)preserve_color(bool): Giữ nguyên màu sắc (default: True)
Returns:
ProcessingResult: Object chứa kết quả xử lý
check_image_quality(image_path)
Kiểm tra chất lượng ảnh và đánh giá các metrics.
Returns:
tuple(bool, dict, np.ndarray): (is_good, quality_info_dict, enhanced_image)
preprocess_image_for_api(image_path, provider="google")
Tiền xử lý ảnh tối ưu cho các API nhà cung cấp.
Parameters:
provider: "google", "anthropic", hoặc "local"
Returns:
tuple(bool, dict, str): (success, processing_info, output_path)
Quality Enhancement Functions
enhance_image(image_path, output_path=None)
Tăng cường chất lượng ảnh một cách nhẹ nhàng.
enhance_image_for_ocr(image_path, output_path=None)
Tối ưu ảnh đặc biệt cho OCR (chuyển binary).
Orientation & Skew Functions
detect_skew(image_path)
Phát hiện góc nghiêng của ảnh.
correct_skew(image_path, angle=None)
Sửa góc nghiêng của ảnh.
rotate_image(image_path, angle)
Xoay ảnh theo góc cho trước.
⚙️ Cấu hình nâng cao
GPU Configuration
from magicimg import ImageProcessor
# Cấu hình GPU tùy chỉnh
config = {
"use_gpu": True,
"gpu_id": 0,
"gpu_memory_limit": 0.7,
"batch_size": 4,
"optimize_for_gpu": True
}
processor = ImageProcessor(config=config)
result = processor.process_image("input.jpg")
Quality Thresholds
# Cấu hình ngưỡng chất lượng
config = {
"min_blur_index": 100.0, # Tăng yêu cầu độ nét
"min_brightness": 200.0, # Tăng yêu cầu độ sáng
"min_contrast": 60.0, # Tăng yêu cầu độ tương phản
"min_resolution": (1200, 1600) # Tăng độ phân giải tối thiểu
}
processor = ImageProcessor(config=config)
Processing Modes
High Quality Mode (cho ảnh quan trọng)
config = {
"min_blur_index": 120.0,
"min_brightness": 220.0,
"min_contrast": 70.0,
"min_resolution": (1500, 2000)
}
result = magicimg.process_image("input.jpg", config=config, preserve_color=True)
Fast Processing Mode (cho batch processing)
config = {
"min_blur_index": 60.0,
"min_brightness": 160.0,
"min_contrast": 40.0,
"skip_rotation": True
}
result = magicimg.process_image("input.jpg", config=config)
OCR Optimization Mode
result = magicimg.preprocess_for_ocr("input.jpg", preserve_color=False)
# preserve_color=False -> chuyển binary cho OCR tối ưu
🔧 Debugging & Troubleshooting
Enable Debug Mode
processor = ImageProcessor(debug_dir="./debug/")
result = processor.process_image("input.jpg")
# Debug images sẽ được lưu trong ./debug/
Common Issues
1. GPU không được phát hiện
# Kiểm tra CUDA
python -c "import torch; print(torch.cuda.is_available())"
# Nếu False, cài đặt PyTorch với CUDA
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu118
2. Tesseract error
# Windows: Thêm Tesseract vào PATH
set PATH=%PATH%;C:\Program Files\Tesseract-OCR
# Linux: Cài đặt Tesseract
sudo apt-get install tesseract-ocr
3. Memory errors với ảnh lớn
# Giảm batch_size
config = {"batch_size": 2, "gpu_memory_limit": 0.5}
processor = ImageProcessor(config=config)
System Information
import magicimg
magicimg.print_system_info()
# In thông tin hệ thống và dependencies
📊 Performance Tips
1. Batch Processing
from magicimg import ImageProcessor
processor = ImageProcessor(config={"batch_size": 8})
# Xử lý nhiều ảnh cùng lúc
image_paths = ["img1.jpg", "img2.jpg", "img3.jpg"]
for path in image_paths:
result = processor.process_image(path)
print(f"Processed {path}: {result.success}")
2. Memory Management
# Sử dụng context manager cho GPU
from magicimg.core import gpu_memory_manager
with gpu_memory_manager():
result = magicimg.process_image("large_image.jpg")
3. Preserve Color vs OCR Mode
# Cho ảnh cần giữ chất lượng cao
result = magicimg.process_image("photo.jpg", preserve_color=True)
# Cho text recognition
result = magicimg.preprocess_for_ocr("document.jpg", preserve_color=False)
🧪 Testing
Run API Consistency Tests
# Test tất cả API functions
python -c "
import magicimg
print('Testing basic APIs...')
result1 = magicimg.check_image_quality('input.jpg')
result2 = magicimg.process_image('input.jpg')
result3 = magicimg.preprocess_image_for_api('input.jpg')
print('All APIs working correctly!')
"
Performance Benchmark
import time
import magicimg
start = time.time()
result = magicimg.process_image("test.jpg")
end = time.time()
print(f"Processing time: {end-start:.2f}s")
print(f"Success: {result.success}")
📝 Examples
Complete Processing Pipeline
import magicimg
def process_document(input_path, output_dir="./output/"):
"""Xử lý document hoàn chỉnh"""
# 1. Kiểm tra chất lượng
is_good, quality_info, enhanced = magicimg.check_image_quality(input_path)
print(f"Quality score: {quality_info['quality_score']:.2f}")
# 2. Xử lý với preserve color
result = magicimg.process_image(
input_path,
output_path=f"{output_dir}/processed.jpg",
preserve_color=True
)
# 3. Tạo version cho OCR
ocr_result = magicimg.preprocess_for_ocr(
input_path,
output_path=f"{output_dir}/ocr_ready.jpg",
preserve_color=False
)
# 4. API processing
api_success, api_info, api_path = magicimg.preprocess_image_for_api(
input_path,
provider="google",
output_dir=output_dir
)
return {
"quality": quality_info,
"processed": result.success,
"ocr_ready": ocr_result.success,
"api_ready": api_success,
"steps": result.processing_steps
}
# Sử dụng
results = process_document("document.jpg")
print(results)
🆕 Changelog v1.0.6
Fixed
- ✅ Sửa lỗi API consistency trong wrapper functions
- ✅ Sửa lỗi unpack ProcessingResult objects
- ✅ Cải thiện type annotations cho tất cả functions
- ✅ Sửa lỗi return type mismatch giữa core và wrapper functions
Improved
- 🚀 Tối ưu memory management cho GPU processing
- 🚀 Cải thiện error handling trong tất cả API functions
- 🚀 Thêm preserve_color option cho flexibility
- 🚀 Enhanced debugging capabilities
Added
- ➕ API consistency test suite
- ➕ Comprehensive error reporting
- ➕ Better documentation với examples
🤝 Contributing
- Fork repository
- Tạo feature branch (
git checkout -b feature/AmazingFeature) - Commit changes (
git commit -m 'Add some AmazingFeature') - Push to branch (
git push origin feature/AmazingFeature) - Tạo Pull Request
📄 License
Distributed under the MIT License. See LICENSE for more information.
🙋♂️ Support
- 📧 Email: shumi2011@gmail.com
- 🐛 Issues: GitHub Issues
- 📖 Documentation: Full Docs
Made with ❤️ by MagicImg Team
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file magicimg-1.0.7.tar.gz.
File metadata
- Download URL: magicimg-1.0.7.tar.gz
- Upload date:
- Size: 35.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.10.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
35ed3de59f6a29b43922594098376fcfbd704892541f39fd0ae8f5bda2f17f64
|
|
| MD5 |
788c00361f09504fb7742d23e1f58648
|
|
| BLAKE2b-256 |
982878ee0354b8f6deed46f57d25b34fa4b5a2ca1abf2bd719f28f1e8d711abe
|
File details
Details for the file magicimg-1.0.7-py3-none-any.whl.
File metadata
- Download URL: magicimg-1.0.7-py3-none-any.whl
- Upload date:
- Size: 33.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.10.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
2a2587833e3e8d8b9cb6635e5036babe0f654362e49e08620f1e687441cb3dec
|
|
| MD5 |
a5df59fc46e5d2cdfd0439e5aa7620e7
|
|
| BLAKE2b-256 |
f9ab5d7da12a9066224c3898b92b072ac83514c0cb66c33190903f24238ab554
|