为了帮助你完成基于Python和OpenCV的图像处理软件项目,我将为你提供一个基本的框架代码。这个框架将涵盖文档中提到的主要功能。你可以根据具体需求进一步扩展和完善这些功能。
### 项目结构
```
image_processor/
│
├── main.py
├── image_utils.py
├── gui.py
└── README.md
```
### 1. `main.py` - 主程序入口
```python
import tkinter as tk
from tkinter import filedialog, messagebox
import cv2
import numpy as np
from PIL import Image, ImageTk
from image_utils import ImageProcessor
from gui import Application
def main():
root = tk.Tk()
app = Application(root)
root.mainloop()
if __name__ == "__main__":
main()
```
### 2. `image_utils.py` - 图像处理工具
```python
import cv2
import numpy as np
class ImageProcessor:
def __init__(self):
self.image = None
def load_image(self, path):
self.image = cv2.imread(path)
return self.image
def save_image(self, path, format=None):
if format:
cv2.imwrite(path, self.image, [int(cv2.IMWRITE_JPEG_QUALITY), 90])
else:
cv2.imwrite(path, self.image)
def resize_image(self, width, height):
self.image = cv2.resize(self.image, (width, height))
def rotate_image(self, angle):
(h, w) = self.image.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
self.image = cv2.warpAffine(self.image, M, (w, h))
def crop_image(self, x, y, width, height):
self.image = self.image[y:y+height, x:x+width]
def adjust_brightness(self, value):
hsv = cv2.cvtColor(self.image, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(hsv)
lim = 255 - value
v[v > lim] = 255
v[v <= lim] += value
final_hsv = cv2.merge((h, s, v))
self.image = cv2.cvtColor(final_hsv, cv2.COLOR_HSV2BGR)
def adjust_contrast(self, value):
alpha = float(131 * (value + 127)) / (127 * (131 - value))
gamma = 127 * (1 - alpha)
self.image = cv2.addWeighted(self.image, alpha, self.image, 0, gamma)
def auto_correct(self):
# Simple auto-correction using CLAHE
lab = cv2.cvtColor(self.image, cv2.COLOR_BGR2LAB)
l, a, b = cv2.split(lab)
clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8, 8))
cl = clahe.apply(l)
limg = cv2.merge((cl, a, b))
self.image = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)
def draw_histogram(self):
hist = cv2.calcHist([self.image], [0], None, [256], [0, 256])
return hist
def compress_image(self, quality):
_, encoded_image = cv2.imencode('.jpg', self.image, [int(cv2.IMWRITE_JPEG_QUALITY), quality])
self.image = cv2.imdecode(encoded_image, 1)
def get_image_info(self):
return {
"filename": "example.jpg",
"file_size": self.image.nbytes,
"dimensions": self.image.shape[:2],
"position": (0, 0)
}
```
### 3. `gui.py` - 图形用户界面
```python
import tkinter as tk
from tkinter import filedialog, messagebox
from PIL import Image, ImageTk
from image_utils import ImageProcessor
class Application:
def __init__(self, master):
self.master = master
self.master.title("Python Image Processor")
self.processor = ImageProcessor()
self.image_label = tk.Label(master)
self.image_label.pack()
self.menu = tk.Menu(master)
self.master.config(menu=self.menu)
file_menu = tk.Menu(self.menu, tearoff=0)
self.menu.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="Open", command=self.open_image)
file_menu.add_command(label="Save", command=self.save_image)
file_menu.add_command(label="Save As", command=self.save_image_as)
file_menu.add_command(label="Rename", command=self.rename_image)
file_menu.add_command(label="Clear", command=self.clear_image)
file_menu.add_command(label="Exit", command=self.master.quit)
edit_menu = tk.Menu(self.menu, tearoff=0)
self.menu.add_cascade(label="Edit", menu=edit_menu)
edit_menu.add_command(label="Zoom In", command=self.zoom_in)
edit_menu.add_command(label="Zoom Out", command=self.zoom_out)
edit_menu.add_command(label="Rotate Left", command=lambda: self.rotate_image(90))
edit_menu.add_command(label="Rotate Right", command=lambda: self.rotate_image(-90))
edit_menu.add_command(label="Crop", command=self.crop_image)
edit_menu.add_command(label="Auto Correct", command=self.auto_correct)
edit_menu.add_command(label="Adjust Brightness", command=self.adjust_brightness)
edit_menu.add_command(label="Adjust Contrast", command=self.adjust_contrast)
edit_menu.add_command(label="Resize", command=self.resize_image)
edit_menu.add_command(label="Color Balance", command=self.color_balance)
edit_menu.add_command(label="Red Eye Removal", command=self.remove_red_eye)
view_menu = tk.Menu(self.menu, tearoff=0)
self.menu.add_cascade(label="View", menu=view_menu)
view_menu.add_command(label="Draw Histogram", command=self.draw_histogram)
view_menu.add_command(label="Image Info", command=self.show_image_info)
def open_image(self):
file_path = filedialog.askopenfilename(filetypes=[("Image files", "*.jpg *.png *.bmp")])
if file_path:
self.processor.load_image(file_path)
self.display_image()
def save_image(self):
if self.processor.image is not None:
file_path = filedialog.asksaveasfilename(defaultextension=".jpg", filetypes=[("JPEG", "*.jpg"), ("PNG", "*.png"), ("BMP", "*.bmp")])
if file_path:
self.processor.save_image(file_path)
def save_image_as(self):
if self.processor.image is not None:
file_path = filedialog.asksaveasfilename(defaultextension=".jpg", filetypes=[("JPEG", "*.jpg"), ("PNG", "*.png"), ("BMP", "*.bmp")])
if file_path:
self.processor.save_image(file_path)
def rename_image(self):
if self.processor.image is not None:
new_name = filedialog.asksaveasfilename(defaultextension=".jpg", filetypes=[("JPEG", "*.jpg"), ("PNG", "*.png"), ("BMP", "*.bmp")])
if new_name:
self.processor.save_image(new_name)
def clear_image(self):
self.processor.image = None
self.display_image()
def display_image(self):
if self.processor.image is not None:
img = Image.fromarray(cv2.cvtColor(self.processor.image, cv2.COLOR_BGR2RGB))
img = ImageTk.PhotoImage(img)
self.image_label.config(image=img)
self.image_label.image = img
def zoom_in(self):
if self.processor.image is not None:
self.processor.resize_image(self.processor.image.shape[1] * 1.2, self.processor.image.shape[0] * 1.2)
self.display_image()
def zoom_out(self):
if self.processor.image is not None:
self.processor.resize_image(self.processor.image.shape[1] * 0.8, self.processor.image.shape[0] * 0.8)
self.display_image()
def rotate_image(self, angle):
if self.processor.image is not None:
self.processor.rotate_image(angle)
self.display_image()
def crop_image(self):
if self.processor.image is not None:
x = int(input("Enter x coordinate: "))
y = int(input("Enter y coordinate: "))
width = int(input("Enter width: "))
height = int(input("Enter height: "))
self.processor.crop_image(x, y, width, height)
self.display_image()
def auto_correct(self):
if self.processor.image is not None:
self.processor.auto_correct()
self.display_image()
def adjust_brightness(self):
if self.processor.image is not None:
value = int(input("Enter brightness value (-100 to 100): "))
self.processor.adjust_brightness(value)
self.display_image()
def adjust_contrast(self):
if self.processor.image is not None:
value = int(input("Enter contrast value (-100 to 100): "))
self.processor.adjust_contrast(value)
self.display_image()
def resize_image(self):
if self.processor.image is not None:
width = int(input("Enter new width: "))
height = int(input("Enter new height: "))
self.processor.resize_image(width, height)
self.display_image()
def color_balance(self):
if self.processor.image is not None:
red = int(input("Enter red balance (-100 to 100): "))
green = int(input("Enter green balance (-100 to 100): "))
blue = int(input("Enter blue balance (-100 to 100): "))
# Implement color balance logic here
pass
def remove_red_eye(self):
if self.processor.image is not None:
# Implement red eye removal logic here
pass
def draw_histogram(self):
if self.processor.image is not None:
hist = self.processor.draw_histogram()
# Display histogram using matplotlib or another library
pass
def show_image_info(self):
if self.processor.image is not None:
info = self.processor.get_image_info()
messagebox.showinfo("Image Info", f"Filename: {info['filename']}\nFile Size: {info['file_size']} bytes\nDimensions: {info['dimensions']}\nPosition: {info['position']}")
if __name__ == "__main__":
root = tk.Tk()
app = Application(root)
root.mainloop()
```
### 4. `README.md` - 项目说明
```markdown
# Python Image Processor
## Overview
This project is a simple image processing application built using Python and OpenCV. It provides basic functionalities for opening, editing, and saving images.
## Features
- File operations: Open, Save, Save As, Rename, Clear
- Image editing: Zoom In, Zoom Out, Rotate Left, Rotate Right, Crop, Auto Correct, Adjust Brightness, Adjust Contrast, Resize, Color Balance, Red Eye Removal
- Other features: Draw Histogram, Show Image Info
## Requirements
- Python 3.x
- OpenCV
- Tkinter
- NumPy
- PIL (Pillow)
## Installation
1. Install the required libraries:
```sh
pip install opencv-python-headless numpy pillow
```
2. Run the application:
```sh
python main.py
```
## Usage
- Open an image from the "File" menu.
- Use the "Edit" menu to apply various image editing operations.
- Use the "View" menu to draw histograms and view image information.
- Save the edited image using the "File" menu.
## Contributing
Feel free to contribute to this project by submitting pull requests or reporting issues.
## License
This project is licensed under the MIT License.
```
### 运行项目
1. 安装所需的库:
```sh
pip install opencv-python-headless numpy pillow
```
2. 运行主程序:
```sh
python main.py
```
这个框架提供了一个基本的图像处理应用程序,涵盖了文档中提到的主要功能。你可以根据需要进一步扩展和完善这些功能。希望这对你有帮助!