山内セミナー(2018/10/24)

関連サイトと資料

講義中に試したプログラム

test1.py
class Car:
    def __init__(self, color = 'white'):
        self.color = color
        self.milage = 0
    
    def drive(self, km):
        self.milage += km
        msg = '{0}kmドライブしました。総距離は{1}kmです。'.format(km, self.milage)
        print(msg)
    
car1 = Car()
msg = 'car1の色は{0}です。'.format(car1.color)
print(msg)
    
car2 = Car('red')
msg = 'car2の色は{0}です。'.format(car2.color)
print(msg)
    
car1.drive(100)
car2.drive(1000)
car1.drive(10000)

test2.py
class Car:
    maker = 'TOYOTA' #クラス変数
    count = 0        #クラス変数
    
    def __init__(self, color = 'white'):
        Car.countup()
        self.mynumber = Car.count
        self.color = color
        self.milage = 0
    
    def drive(self, km):
        self.milage += km
        msg = '{0}kmドライブしました。総距離は{1}kmです。'.format(km, self.milage)
        print(msg)
    
    @classmethod
    def countup(cls):
        cls.count += 1
        msg = '出荷台数:{0}'.format(cls.count)
        print(msg)
        
msg = '車のメーカーは{0}です。'.format(Car.maker)
print(msg)
    
car1 = Car()
msg = 'car1の番号は{0}です。'.format(car1.mynumber)
print(msg)
    
car2 = Car('red')
msg = 'car2の番号は{0}です。'.format(car2.mynumber)
print(msg)

test3.py
class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def hello(self):
        msg = 'やあ、{0}!'.format(self.name)
        print(msg)
    
class Player(Person):
    def __init__(self, name, age, number, position):
        Person.__init__(self, name, age)
        self.number = number
        self.position = position
    
    # def hello(self):
    #     msg = 'やあ、{0} {1}!'.format(self.name, self.position)
    #     print(msg)
    
p1 = Person('安倍晋三', 63)
p1.hello()
    
p2 = Player('ダルビッシュ有', 31, 21, '投手')
p2.hello()

test4.py
class Goods:
    def __init__(self, name, price):
        self.__data = {'name': name, 'price': price}
    
    @property
    def name(self):
        return self.__data['name']
    
    @name.setter
    def name(self, value):
        self.__data['name'] = value
    
    @property
    def price(self):
        price = self.__data['price']
        price_str = '{0} 円'.format(price)
        return price_str
    
    @price.setter
    def price(self, value):
        self.__data['price'] = value

    
shoes = Goods('dream', 6800)
msg = '{0}の価格は{1}です!'.format(shoes.name, shoes.price)
print(msg)
    
shoes.name = '陸王'
msg = '{0}の価格は{1}です!'.format(shoes.name, shoes.price)
print(msg)
    
shoes.price = 10000
msg = '{0}の価格は{1}です!'.format(shoes.name, shoes.price)
print(msg)

test5.py
from PIL import Image
from PIL.ExifTags import TAGS
from PIL.ExifTags import GPSTAGS
    
def get_exif_of_image(file):
    im = Image.open(file)
    
    try:
        exif = im._getexif()
    except AttributeError:
        return {}
    
    exif_table = {}
    for tag_id, value in exif.items():
        tag = TAGS.get(tag_id, tag_id)
    
        if tag == "GPSInfo":
            gps_data = {}
            for t in value:
                sub_tag = GPSTAGS.get(t, t)
                gps_data[sub_tag] = value[t]
    
            exif_table[tag] = gps_data
        else:
            exif_table[tag] = value
    
    return exif_table
    
def convertToDegress(value):
    d0 = value[0][0]
    d1 = value[0][1]
    d = float(d0) / float(d1)
    
    m0 = value[1][0]
    m1 = value[1][1]
    m = float(m0) / float(m1)
    
    s0 = value[2][0]
    s1 = value[2][1]
    s = float(s0) / float(s1)
    
    return d + (m / 60.0) + (s / 3600.0)
    
def convertToLength(value):
    d0 = value[0]
    d1 = value[1]
    d = float(d0) / float(d1)
    
    return d
    
target = '2015-06-22 15.14.21.jpg'
ExifDict = get_exif_of_image(target)
    
print('写真のファイル名:{0}'.format(target))
for key in ExifDict:
    if key == 'GPSInfo':
        gps_info = ExifDict["GPSInfo"]
    
        gpsLatitude = gps_info["GPSLatitude"]
        gpsLongitude = gps_info["GPSLongitude"]
        gpsLatitudeRef = gps_info["GPSLatitudeRef"]
        gpsLongitudeRef = gps_info["GPSLongitudeRef"]
    
        gpsAltitude = gps_info["GPSAltitude"]
        gpsAltitudeRef = gps_info["GPSAltitudeRef"]
    
        lat = convertToDegress(gpsLatitude)
        if gpsLatitudeRef != "N":
            lat = 0 - lat
    
        lon = convertToDegress(gpsLongitude)
        if gpsLongitudeRef != "E":
            lon = 0 - lon
    
        alt = convertToLength(gpsAltitude)
    
        msg = 'key:GPSInfo, value:緯度={0} 経度={1} 高度={2}'.format(lat, lon, alt)
        print(msg)

クラス

サンプルプログラム(1)

クラスは、オブジェクト指向を実現するための要となるものです。 具体的には、プログラミング対象をオブジェクトとしてとらえ、 各オブジェクト内に処理とデータを持たせるというものです。 以下のプログラムは、Carクラスを定義したものです。 ただし、データも処理もありませんが...

クラス1.py
class Car:
    pass #何もしない
	
car1 = Car()
car2 = Car()

では、Carクラスに色と走行距離をデータとして持たせ、指定した距離だけ走行する処理を定義してみます。

クラス2.py
class Car:
    def __init__(self, color = 'white'):
        self.color = color
        self.milage = 0
	
    def drive(self, km):
        self.milage += km
        msg = '{0}kmドライブしました。総距離は{1}kmです。'.format(km, self.milage)
        print(msg)
	
car1 = Car()
msg = 'car1の色は{0}です。'.format(car1.color)
print(msg)
	
car2 = Car('red')
msg = 'car2の色は{0}です。'.format(car2.color)
print(msg)
	
car1.drive(100)
car2.drive(1000)

次に、クラス変数とクラスメソッドを定義してみます。

クラス3.py
class Car:
    maker = 'TOYOTA' #クラス変数
    count = 0        #クラス変数
    
    def __init__(self, color = 'white'):
        Car.countup()
        self.mynumber = Car.count
        self.color = color
        self.milage = 0
	
    def drive(self, km):
        self.milage += km
        msg = '{0}kmドライブしました。総距離は{1}kmです。'.format(km, self.milage)
        print(msg)
	
    @classmethod
    def countup(cls):
        cls.count += 1
        msg = '出荷台数:{0}'.format(cls.count)
        print(msg)
        
msg = '車のメーカーは{0}です。'.format(Car.maker)
print(msg)
	
car1 = Car()
msg = 'car1の番号は{0}です。'.format(car1.mynumber)
print(msg)
	
car2 = Car('red')
msg = 'car2の番号は{0}です。'.format(car2.mynumber)
print(msg)

次に、クラスの継承を試してみます。

クラス4.py
class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
	
    def hello(self):
        msg = 'やあ、{0}!'.format(self.name)
        print(msg)
	
class Player(Person):
    def __init__(self, name, age, number, position):
        Person.__init__(self, name, age)
        self.number = number
        self.position = position
	
    def hello(self):
        msg = 'やあ、{0} {1}!'.format(self.name, self.position)
        print(msg)
	
p1 = Person('安倍晋三', 63)
p1.hello()
	
p2 = Player('ダルビッシュ有', 31, 21, '投手')
p2.hello()

次に、プロパティの機能を試してみます。

クラス5.py
class Goods:
    def __init__(self, name, price):
        self.__data = {'name': name, 'price': price}
	
    @property
    def name(self):
        return self.__data['name']
    
    @name.setter
    def name(self, value):
        self.__data['name'] = value
	
    @property
    def price(self):
        price = self.__data['price']
        price_str = '{0} 円'.format(price)
        return price_str
	
shoes = Goods('dream', 6800)
msg = '{0}の価格は{1}です!'.format(shoes.name, shoes.price)
print(msg)
	
shoes.name = '陸王'
msg = '{0}の価格は{1}です!'.format(shoes.name, shoes.price)
print(msg)
	
shoes.price = 10000
msg = '{0}の価格は{1}です!'.format(shoes.name, shoes.price)
print(msg)

Exif

サンプルプログラム(1)

2012-09-11 13.20.30.jpg(撮影場所1)

2015-06-22 15.14.21.jpg(撮影場所2)

写真のExif読み出し1.py
from PIL import Image
from PIL.ExifTags import TAGS
	
def get_exif_of_image(file):
	im = Image.open(file)
	
	try:
		exif = im._getexif()
	except AttributeError:
		return {}
	
	exif_table = {}
	for tag_id, value in exif.items():
		tag = TAGS.get(tag_id, tag_id)
		exif_table[tag] = value
	
	return exif_table
	
target = '2012-09-11 13.20.30.jpg'
ExifDict = get_exif_of_image(target)
	
for key in ExifDict:
	print('key:{0}, value:{1}'.format(key, ExifDict[key]))

写真のExif読み出し2.py
from PIL import Image
from PIL.ExifTags import TAGS
from PIL.ExifTags import GPSTAGS
	
def get_exif_of_image(file):
	im = Image.open(file)
	
	try:
		exif = im._getexif()
	except AttributeError:
		return {}
	
	exif_table = {}
	for tag_id, value in exif.items():
		tag = TAGS.get(tag_id, tag_id)
	
		if tag == "GPSInfo":
			gps_data = {}
			for t in value:
				sub_tag = GPSTAGS.get(t, t)
				gps_data[sub_tag] = value[t]
	
			exif_table[tag] = gps_data
		else:
			exif_table[tag] = value
	
	return exif_table
	
def convertToDegress(value):
	d0 = value[0][0]
	d1 = value[0][1]
	d = float(d0) / float(d1)
	
	m0 = value[1][0]
	m1 = value[1][1]
	m = float(m0) / float(m1)
	
	s0 = value[2][0]
	s1 = value[2][1]
	s = float(s0) / float(s1)
	
	return d + (m / 60.0) + (s / 3600.0)
	
def convertToLength(value):
	d0 = value[0]
	d1 = value[1]
	d = float(d0) / float(d1)
	
	return d
	
target = '2012-09-11 13.20.30.jpg'
ExifDict = get_exif_of_image(target)
	
print('写真のファイル名:{0}'.format(target))
for key in ExifDict:
	if key == 'GPSInfo':
		gps_info = ExifDict["GPSInfo"]
	
		gpsLatitude = gps_info["GPSLatitude"]
		gpsLongitude = gps_info["GPSLongitude"]
		gpsLatitudeRef = gps_info["GPSLatitudeRef"]
		gpsLongitudeRef = gps_info["GPSLongitudeRef"]
	
		gpsAltitude = gps_info["GPSAltitude"]
		gpsAltitudeRef = gps_info["GPSAltitudeRef"]
	
		lat = convertToDegress(gpsLatitude)
		if gpsLatitudeRef != "N":
			lat = 0 - lat
	
		lon = convertToDegress(gpsLongitude)
		if gpsLongitudeRef != "E":
			lon = 0 - lon
	
		alt = convertToLength(gpsAltitude)
	
		msg = 'key:GPSInfo, value:緯度={0} 経度={1} 高度={2}'.format(lat, lon, alt)
		print(msg)
	else:
		print('key:{0}, value:{1}'.format(key, ExifDict[key]))

アニメーションgif

サンプルプログラム(1)

アニメーションgif.py
from PIL import Image, ImageDraw
	
images = []
	
width = 200
height = 300
center = width // 2
color_1 = (255, 0, 0)
color_2 = (0, 255, 0)
max_radius = int(center * 1.5)
step = 8
	
for i in range(0, max_radius, step):
    im = Image.new('RGB', (width, height), color_1)
    draw = ImageDraw.Draw(im)
    draw.ellipse((center - i, center - i, center + i, center + i), fill=color_2)
    images.append(im)
	
for i in range(0, max_radius, step):
    im = Image.new('RGB', (width, height), color_2)
    draw = ImageDraw.Draw(im)
    draw.ellipse((center - i, center - i, center + i, center + i), fill=color_1)
    images.append(im)
	
images[0].save('a1.gif', save_all=True, append_images=images[1:], optimize=False, duration=40, loop=0)