技巧:用python内部支持多种参数类型的天然保留方法的重载,如__id__()
# 编写代码重载加减乘除四则运算,实现图像的加减乘除
# 原理是将图像每一个像素点的rgb三个值作对应的加减乘除运算
from PIL import Image
import numpy as np
class ImageObject:
def __init__(self, path = ''):
self.path = path
try:
self.data = np.array(Image.open(path)) #调用numpy库的array函数生成一个三维数组
except:
self.data = None
def __add__(self, other):
image = ImageObject()
try:
image.data = np.mod(self.data + other.data, 255) #numpy数据库取模函数
except:
image.data = self.data
return image
def __sub__(self, other):
image = ImageObject()
try:
image.data = np.mod(self.data - other.data, 255)
except:
image.data = self.data
return image
def __mul__(self, factor):
image = ImageObject()
try:
image.data = np.mod(self.data * factor, 255)
except:
image.data = self.data
return image
def __truediv__(self, factor):
image = ImageObject()
try:
image.data = np.mod(self.data // factor, 255)
except:
image.data = self.data
return image
def saveImage(self, path):
try:
im = Image.fromarray(self.data)
im.save(path)
return True
except:
return False
a = ImageObject("***")
b = ImageObject("***")
(a + b).saveImage("path****")
(a - b).saveImage("path****")
(a * b).saveImage("path****")
(a / b).saveImage("path****")
以上所有内容来自嵩天老师《python面向对象精讲》,为学习截图与随堂笔记整理,方便日后复习使用