用类的继承,实现python简单的图像处理
时间: 2024-05-25 07:05:45 浏览: 8
以下是一个简单的图像处理类的继承实现,包括灰度化、二值化和边缘检测:
```python
import cv2
class ImageProcessor:
def __init__(self, filename):
self.filename = filename
self.image = cv2.imread(filename)
def grayscale(self):
gray = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY)
cv2.imwrite("grayscale_" + self.filename, gray)
def binary(self, threshold=127):
gray = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray, threshold, 255, cv2.THRESH_BINARY)
cv2.imwrite("binary_" + self.filename, binary)
def edge_detection(self):
gray = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 100, 200)
cv2.imwrite("edge_" + self.filename, edges)
class GrayscaleImageProcessor(ImageProcessor):
def __init__(self, filename):
super().__init__(filename)
def process(self):
self.grayscale()
class BinaryImageProcessor(ImageProcessor):
def __init__(self, filename, threshold=127):
super().__init__(filename)
self.threshold = threshold
def process(self):
self.binary(self.threshold)
class EdgeImageProcessor(ImageProcessor):
def __init__(self, filename):
super().__init__(filename)
def process(self):
self.edge_detection()
```
使用示例:
```python
# 创建图像处理器对象
processor = ImageProcessor("image.jpg")
# 灰度化图像
processor.grayscale()
# 二值化图像
processor.binary()
# 边缘检测
processor.edge_detection()
# 创建灰度化图像处理器对象
grayscale_processor = GrayscaleImageProcessor("image.jpg")
# 处理灰度化图像
grayscale_processor.process()
# 创建二值化图像处理器对象
binary_processor = BinaryImageProcessor("image.jpg", threshold=200)
# 处理二值化图像
binary_processor.process()
# 创建边缘检测图像处理器对象
edge_processor = EdgeImageProcessor("image.jpg")
# 处理边缘检测图像
edge_processor.process()
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)