## 2018年11月12日月曜日

### Python - 基本的な画像処理(閾値処理、ラベル画像、物体の分離、物体の中心)

コード(Emacs)

Python 3

```#!/usr/bin/env python3
''' 問題7 '''
from PIL import Image
import numpy as np
from scipy import ndimage
import matplotlib.pyplot as plt

print('7.')

NAME = 'building_gray'

IM = np.array(Image.open(f'{NAME}.jpg'))
IM = 1 * (IM < 128)
IM = ndimage.morphology.binary_opening(IM, np.ones((3, 1)), iterations=5)
LABELS, NBR_OBJECTS = ndimage.measurements.label(IM)
CENTERS = ndimage.measurements.center_of_mass(IM, LABELS, range(NBR_OBJECTS))

print(f'物体の数: {NBR_OBJECTS}')
plt.imshow(IM)
for x, y in CENTERS:
plt.plot(y, x, '.')
plt.savefig(f'{NAME}_centers.jpg')
```

```\$ ./sample7.py
7.
/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/scipy/ndimage/measurements.py:1328: RuntimeWarning: invalid value encountered in true_divide
for dir in range(input.ndim)]

\$ pylint sample7.py
************* Module sample7
sample7.py:16:0: C0103: Constant name "centers" doesn't conform to UPPER_CASE naming style (invalid-name)

------------------------------------------------------------------
Your code has been rated at 9.38/10

\$ pylint sample7.py

-------------------------------------------------------------------
Your code has been rated at 10.00/10 (previous run: 9.38/10, +0.62)

\$
```