コアラとクマの画像を自動生成する

機械学習、特にディープラーニング（深層学習）ではよく、画像の分類が題材として用いられます。ですがそこで用いる題材は、決まったものばかりな印象がありますので、新しい題材を提供すべく、コアラとクマの画像を大量に自動生成するためのスクリプトを書いてみました。

以下がそのコードです。

```python
from PIL import Image, ImageDraw
from IPython.display import HTML
import random

def koala_or_bear(bear=False, rotate=False, resize=False, gray=True, black=True, others=False):
    r = random.randint(100, 255)
    g = random.randint(100, 255)
    b = random.randint(100, 255)
    if gray:
        r = g = b

    im = Image.new('RGB', (500, 500), (r, g, b))
    draw = ImageDraw.Draw(im)

    if others:
        for i in range(100):
            r = random.randint(100, 255)
            g = random.randint(100, 255)
            b = random.randint(100, 255)
            if gray:
                r = g = b

            x1 = random.randint(0, 500)
            y1 = random.randint(0, 500)
            x2 = random.randint(0, 500)
            y2 = random.randint(0, 500)
            draw.ellipse((x1, x2, y1, y2), fill=(r, g, b))

    r = random.randint(0, 200)
    g = random.randint(0, 200)
    b = random.randint(0, 200)
    if black:
        r = g = b = 1

    dx1 = random.randint(-10, 0)
    dx2 = random.randint(0, 10)
    dy1 = random.randint(-10, 0)
    dy2 = random.randint(0, 10)
    if bear:
        draw.ellipse((200 + dx1, 200 + dy1, 300 + dx2, 300 + dy2), fill=(r, g, b))
    else:
        draw.ellipse((210 + dx1, 210 + dy1, 290 + dx2, 290 + dy2), fill=(r, g, b))

    dx1 = random.randint(-5, 10)
    dx2 = random.randint(-10, 5)
    dy1 = random.randint(-5, 10)
    dy2 = random.randint(-10, 5)
    cx1 = random.randint(160, 180)
    cx2 = random.randint(230, 250)
    if bear:
        #draw.ellipse((160 + dx1, 160 + dy1, 230 + dx2, 230 + dy2), fill=(r, g, b))
        draw.ellipse((160 + dx1, cx1 + dy1, 230 + dx2, cx2 + dy2), fill=(r, g, b))
    else:
        #draw.ellipse((160 + dx1, 190 + dy1, 230 + dx2, 260 + dy2), fill=(r, g, b))
        draw.ellipse((160 + dx1, 210 + dy1, 230 + dx2, 280 + dy2), fill=(r, g, b))
    dx1 = random.randint(-5, 10)
    dx2 = random.randint(-10, 5)
    dy1 = random.randint(-5, 10)
    dy2 = random.randint(-10, 5)
    if bear:
        #draw.ellipse((270 + dx1, 160 + dy1, 340 + dx2, 230 + dy2), fill=(r, g, b))
        draw.ellipse((270 + dx1, cx1 + dy1, 340 + dx2, cx2 + dy2), fill=(r, g, b))
    else:
        #draw.ellipse((270 + dx1, 190 + dy1, 340 + dx2, 260 + dy2), fill=(r, g, b))
        draw.ellipse((270 + dx1, 210 + dy1, 340 + dx2, 280 + dy2), fill=(r, g, b))

    if rotate:
        angle = random.randint(0, 360)
        im = im.rotate(angle)

    if resize:
        h = random.randint(100, 200)
        center = random.randint(220, 280)
        size = 384
        if type(resize) == int:
            size = resize
        im = im.resize(size=(size, size), resample=Image.LANCZOS, box=(max(0, center - h), max(0, center - h), 
                                                                    min(500, center + h), min(500, center + h)))

    return im
```

# 使用例

```python
im = koala_or_bear()
im.save('image.jpg', quality=95)
HTML('<img src="image.jpg">')
```



![image.jpg](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/211162/b2c4c509-5f1f-3afb-7c72-a41c9cc27515.jpeg)


## コアラの画像ととクマの画像を大量に生成

```python
!mkdir koala_or_bear

num_data = 16
for i in range(num_data):
    im = koala_or_bear(bear=False)
    im.save("koala_or_bear/koala_{}.jpg".format(i), quality=95)

for i in range(num_data):
    im = koala_or_bear(bear=True)
    im.save("koala_or_bear/bear_{}.jpg".format(i), quality=95)
```


## 生成したコアラとクマの画像を読み込み

```python
from PIL import Image

koalas = []
for i in range(num_data):
    koala = Image.open("koala_or_bear/koala_{}.jpg".format(i))
    koalas.append(koala)
    
bears = []
for i in range(num_data):
    bear = Image.open("koala_or_bear/bear_{}.jpg".format(i))
    bears.append(bear)
```

## 画像の確認

```python
%matplotlib inline
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(10,10))
for i in range(num_data):
    ax = fig.add_subplot(4, 4, i+1)
    ax.axis('off')
    ax.set_title('koala_{}'.format(i))
    ax.imshow(koalas[i],cmap=plt.cm.gray, interpolation='none')
plt.show()
```

![output_4_0.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/211162/4bc630f2-9710-9b29-6db3-8baf75961406.png)



```python
%matplotlib inline
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(10,10))
for i in range(num_data):
    ax = fig.add_subplot(4, 4, i+1)
    ax.axis('off')
    ax.set_title('bear_{}'.format(i))
    ax.imshow(bears[i],cmap=plt.cm.gray, interpolation='none')
plt.show()
```

![output_5_0.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/211162/6771e723-5f9a-425d-9ef1-c2d028fd2534.png)


# 画像のバリエーションをもっと増やす

## 回転・拡大

```python
for i in range(num_data):
    im = koala_or_bear(bear=False, rotate=True, resize=True)
    im.save("koala_or_bear/koala_{}.jpg".format(i), quality=95)
    bears = []
    
for i in range(num_data):
    bear = Image.open("koala_or_bear/koala_{}.jpg".format(i))
    bears.append(bear)

fig = plt.figure(figsize=(10,10))
for i in range(num_data):
    ax = fig.add_subplot(4, 4, i+1)
    ax.axis('off')
    ax.set_title('koala_{}'.format(i))
    ax.imshow(bears[i],cmap=plt.cm.gray, interpolation='none')
plt.show()
```

![output_6_0.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/211162/0be3732d-b1e7-f5e3-d489-8b5cb184f907.png)


## 色彩豊かに

```python
for i in range(num_data):
    im = koala_or_bear(bear=False, rotate=True, resize=True, gray=False, black=False)
    im.save("koala_or_bear/koala_{}.jpg".format(i), quality=95)
    bears = []
    
for i in range(num_data):
    bear = Image.open("koala_or_bear/koala_{}.jpg".format(i))
    bears.append(bear)

fig = plt.figure(figsize=(10,10))
for i in range(num_data):
    ax = fig.add_subplot(4, 4, i+1)
    ax.axis('off')
    ax.set_title('koala_{}'.format(i))
    ax.imshow(bears[i],cmap=plt.cm.gray, interpolation='none')
plt.show()
```

![output_7_0.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/211162/a3c7fe6c-f402-5c3b-0a73-c14cca6560b2.png)


## コアラ・クマ以外の謎の物体も自動描画

```python
for i in range(num_data):
    im = koala_or_bear(bear=True, rotate=True, resize=True, gray=False, black=False, others=True)
    im.save("koala_or_bear/bear_{}.jpg".format(i), quality=95)
    bears = []
    
for i in range(num_data):
    bear = Image.open("koala_or_bear/bear_{}.jpg".format(i))
    bears.append(bear)

fig = plt.figure(figsize=(10,10))
for i in range(num_data):
    ax = fig.add_subplot(4, 4, i+1)
    ax.axis('off')
    ax.set_title('bear_{}'.format(i))
    ax.imshow(bears[i],cmap=plt.cm.gray, interpolation='none')
plt.show()
```

![output_8_0.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/211162/c99493b4-8fc4-0f07-505a-7f434a1117c9.png)

# まとめ

機械学習または深層学習による画像分類として使えそうな、コアラの画像・クマの画像を自動生成するツールを作成しました。いろんなバリエーションを作って難易度を調整できると思います。また、セマンティックセグメンテーションの勉強にもいいのではないでしょうか。