システム Python を使うことができる(その場合,Python のインストールは行わない)
システム Python を用いるときは,pip, setuptools の更新は次のコマンドで行う.
sudo apt -y update sudo apt -y install python3-pip python3-setuptools
Ubuntu で,システム Python 以外の Python をインストールしたい場合は pyenv が便利である: 別ページで説明している.
Python の URL: http://www.python.org/
【Python, pip の使い方】
Python, pip は,次のコマンドで起動できる.
【Python 開発環境のインストール】
JupyterLab, spyder, nteract (Python 開発環境) のインストールは, Windows でコマンドプロンプトを管理者として実行し, 次のコマンドを実行.
python -m pip install -U pip setuptools jupyterlab jupyter jupyter-console jupytext nteract_on_jupyter spyder
詳しくは,: 別ページで説明している.
JupyterLab, spyder, nteract (Python 開発環境) のインストール: : 別ページで説明している.
コマンドプロンプトで次のコマンドを実行
python -m pip install -U opencv-python
端末で次のコマンドを実行
sudo apt -y update sudo apt -y install libopencv-dev python3-opencv
端末で次のコマンドを実行
sudo apt -y update sudo apt -y install libopencv-dev python3-opencv python3-opencv-apps
画像ファイル fruits.jpg, home.jpg のダウンロードは, Windows でコマンドプロンプトを管理者として実行し, 次のコマンドを実行.
mkdir c:\image cd c:\image curl -L https://github.com/opencv/opencv/blob/master/samples/data/fruits.jpg?raw=true -o fruits.jpg curl -L https://github.com/opencv/opencv/blob/master/samples/data/home.jpg?raw=true -o home.jpg
上のコマンドがうまく
https://github.com/opencv/opencv/tree/master/samples/data
で公開されている fruits.jpg, home.jpg を使用する(謝辞:画像の作者に感謝します)
Python プログラムを動かす.
Python プログラムを動かすために,
Windows では「python」,
Ubuntu では「python3」などのコマンドを使う.
あるいは,
開発環境や Python コンソール(Jupyter Qt Console,Spyder,PyCharm,PyScripter など)の利用も便利である.
あるいは,オンラインで動くGoogle Colaboratory のノートブックの利用も,場合によっては便利である.
ヒストグラム平坦化
※ Windows の場合には,「IMROOT="/usr/local/image/"」は、「IMROOT="C:/image/"」のように書き換えて実行する.
import numpy as np
import cv2
IMROOT="/usr/local/image/"
KERNSIZE=10
bgr = cv2.imread(IMROOT + "fruits.jpg")
mono = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)
r, dst = cv2.threshold(mono, 0, 255, cv2.THRESH_OTSU)
kernel = np.ones((KERNSIZE, KERNSIZE), np.uint8)
opening = cv2.morphologyEx(dst, cv2.MORPH_OPEN, kernel)
cv2.imshow("opening", opening)
edges, contours, hierarchy = cv2.findContours(opening, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.imshow("edges", edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
画像が表示されるので確認. このあと,ウインドウの右上の「x」をクリックしない.画面の中をクリックしてから,何かのキーを押して閉じる
引き続き次を実行
print( cv2.contourArea(contours[0]) )
x,y,w,h = cv2.boundingRect(contours[0]) aspect_ratio = float(w)/h print( aspect_ratio )
(x,y),(MA,ma),angle = cv2.fitEllipse(contours[0]) print( angle )