Skip to content

Instantly share code, notes, and snippets.

@takatakamanbou
Last active June 21, 2020 07:02
Show Gist options
  • Save takatakamanbou/e253ee84a5a8632a3e8eab828f763737 to your computer and use it in GitHub Desktop.
Save takatakamanbou/e253ee84a5a8632a3e8eab828f763737 to your computer and use it in GitHub Desktop.
PIP2020-11-note2.ipynb
Display the source blob
Display the rendered blob
Raw
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "PIP2020-11-note2.ipynb",
"provenance": [],
"collapsed_sections": [],
"toc_visible": true,
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/gist/takatakamanbou/e253ee84a5a8632a3e8eab828f763737/pip2020-11-note2.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "NI3mY1FGZWgV",
"colab_type": "text"
},
"source": [
"# 2020年度パターン情報処理第11回講義資料その2\n",
"\n",
"この科目のウェブサイトへ https://www-tlab.math.ryukoku.ac.jp/wiki/?PIP/2020\n",
"\n",
"![hoge](https://www-tlab.math.ryukoku.ac.jp/~takataka/course/PIP/PIP-logo-96x96.png)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ffaGVK2o5VWe",
"colab_type": "text"
},
"source": [
"## はじめに"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0IpujRN_Wuib",
"colab_type": "text"
},
"source": [
"### これは何?\n",
"\n",
"これは,Google Colaboratory(以下 Google Colab) という,Google が提供しているサービスを利用して作成した資料です.Notebook と呼びます.クラウド上に仮想的に構築された Linux マシン上で Python のプログラムを実行することができます."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "QRNjWashW4pr",
"colab_type": "text"
},
"source": [
"### Notebook の動かし方\n",
"\n",
"この Notebook では,上の方のセルで作った変数や関数を後のセルで使うことがあります.そのため,上の方のセルを実行せずに下の方を実行すると,エラーになることがあります.上から順に実行していきましょう.\n",
"\n",
"また,メニューの「ランタイム」から,「すべてのセルを実行」したりすることも可能です."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1jfSXIY6VNxP",
"colab_type": "text"
},
"source": [
"## 準備\n",
"\n",
"以下のセルは,プログラムを実行するための準備を行うためのものです.このセルを実行してから,先へ進みましょう."
]
},
{
"cell_type": "code",
"metadata": {
"id": "IFYQk7ONZENz",
"colab_type": "code",
"colab": {}
},
"source": [
"# 科学技術計算のライブラリ NumPy のモジュールを np という名前で使えるようにする\n",
"import numpy as np\n",
"# コンピュータビジョン・画像処理のためのライブラリ OpenCV のモジュール cv2 をインポート\n",
"import cv2\n",
"# Google Colab 上へ/からのファイルのアップロード/ダウンロードのためのほげ\n",
"from google.colab import files"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"colab_type": "code",
"id": "T4eMKID578kx",
"colab": {}
},
"source": [
"from IPython.display import display, Image\n",
"\n",
"### 画像表示用の関数\n",
"#\n",
"def displayImage(img):\n",
" \n",
" if type(img) is np.ndarray: # 渡されたのが np.ndarray だった(OpenCVの画像はこの形式)\n",
" rv, buf = cv2.imencode('.png', img) # PNG形式のバイト列に変換\n",
" if rv:\n",
" display(Image(data = buf.tobytes())) # 変換できたらバイト列を渡して表示\n",
" return\n",
" elif type(img) is str: # 渡されたのが文字列だった\n",
" display(Image(filename = img))\n",
" return\n",
" \n",
" print('displayImage: error')"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "mAp8oXFN3KTk",
"colab_type": "text"
},
"source": [
"## ★ 画素値の補間と画像の拡大"
]
},
{
"cell_type": "code",
"metadata": {
"id": "Mcn5bWtUYUvD",
"colab_type": "code",
"colab": {}
},
"source": [
"# 画像を入手\n",
"! wget -nc https://www-tlab.math.ryukoku.ac.jp/~takataka/course/PIP/lena.jpg\n",
"! ls -l\n",
"# 入手した画像を読み込む\n",
"lena = cv2.imread('lena.jpg', cv2.IMREAD_GRAYSCALE) # グレイスケール画像として読み込む\n",
"# 画像を表示\n",
"displayImage(lena)\n",
"print(lena.shape)"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "yAEO5nJyju9t",
"colab_type": "text"
},
"source": [
"### やってみよう\n",
"以下のセルの r の値をいろいろ変えてみよう"
]
},
{
"cell_type": "code",
"metadata": {
"id": "yWmYrx6Jfq3h",
"colab_type": "code",
"colab": {}
},
"source": [
"# 画像の拡大\n",
"r = 3.7 # 拡大率\n",
"\n",
"px, py = int(180*r), int(220*r)\n",
"w, h = int(100*r), int(100*r)\n",
"\n",
"# 手法その1\n",
"img2 = cv2.resize(lena, None, fx = r, fy = r, interpolation = cv2.INTER_LINEAR)\n",
"\n",
"# 手法その2\n",
"img1 = cv2.resize(lena, None, fx = r, fy = r, interpolation = cv2.INTER_NEAREST)\n",
"\n",
"# 手法その3\n",
"img3 = cv2.resize(lena, None, fx = r, fy = r, interpolation = cv2.INTER_CUBIC)\n",
"\n",
"\n",
"# 拡大した画像の一部を表示\n",
"displayImage(img1[py:py+h, px:px+w]) # 真ん中あたりを切り取って表示\n",
"print(f'↑は最近傍補間(Nearest Neighbor Interpolation)を用いて {r} 倍に拡大した画像')\n",
"print()\n",
"displayImage(img2[py:py+h, px:px+w]) # 真ん中あたりを切り取って表示\n",
"print(f'↑は双線形補間(Bi-Linear Interpolation)を用いて {r} 倍に拡大した画像')\n",
"print()\n",
"displayImage(img3[py:py+h, px:px+w]) # 真ん中あたりを切り取って表示\n",
"print(f'↑は双三次補間(Bi-Cubic Interpolation)を用いて {r} 倍に拡大した画像')"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "msyDqtuDbZqY",
"colab_type": "text"
},
"source": [
"## ★ Hough変換"
]
},
{
"cell_type": "code",
"metadata": {
"id": "VmUXWN6ibij5",
"colab_type": "code",
"colab": {}
},
"source": [
"# 画像を入手\n",
"! wget -nc https://www-tlab.math.ryukoku.ac.jp/~takataka/course/PIP/kapibara640x480.jpg\n",
"! ls -l\n",
"\n",
"# 画像を読み込む\n",
"kapi = cv2.imread('kapibara640x480.jpg') # カラー画像\n",
"\n",
"# 画像を表示\n",
"displayImage(kapi)\n",
"print(kapi.shape)"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "Q7EjVmj7bmQJ",
"colab_type": "code",
"colab": {}
},
"source": [
"### Canny法で特徴点を検出しHough変換する関数\n",
"#\n",
"# thCanny1, thCanny2 は Canny法のパラメータ\n",
"# thHough は Hough変換のパラメータ(票数のしきい値(この数以上票の入ったものだけ採用))\n",
"#\n",
"def HoughTransform(img, thCanny1=100, thCanny2=300, thHough=120):\n",
" \n",
" # グレイスケールに変換\n",
" imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n",
"\n",
" # Canny法でエッジを検出\n",
" imgCanny = cv2.Canny(imgGray, thCanny1, thCanny2, apertureSize = 3)\n",
"\n",
" # Hough変換\n",
" rhoRes, thetaRes = 1, 1*np.pi/180 # (rho, theta)平面を分割する格子の間隔\n",
" lines = cv2.HoughLines(imgCanny, rhoRes, thetaRes, thHough)\n",
" print('(number of detected lines) = ', lines.shape[0])\n",
" \n",
" return imgCanny, lines"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "J_lxc_LxboSk",
"colab_type": "code",
"colab": {}
},
"source": [
"### 画像 img に lines に格納されたパラメータの直線を重ねて描く\n",
"#\n",
"def drawLines(img, lines):\n",
" \n",
" dst = np.copy(img) # 出力用画像\n",
" \n",
" height, width = img.shape[0:2]\n",
"\n",
" for x in lines:\n",
" rho, theta = x[0]\n",
" # (rho, theta) の直線を画像の端までで描く\n",
" if np.pi/4 <= theta and theta <= 3*np.pi/4:\n",
" val = rho / np.sin( theta )\n",
" pt1 = ( 0, int( val ) )\n",
" pt2 = ( width, int( val - width / np.tan( theta ) ) )\n",
" else:\n",
" val = rho / np.cos( theta )\n",
" pt1 = ( int( val ), 0 )\n",
" pt2 = ( int( val - height * np.tan( theta ) ), height )\n",
"\n",
" #print( rho, theta, pt1, pt2 )\n",
" cv2.line(dst, pt1, pt2, ( 0, 0, 255 ), thickness = 2)\n",
" \n",
" return dst"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "vWuQVTDdbqKz",
"colab_type": "code",
"colab": {}
},
"source": [
"# Hough変換してみる\n",
"imgCanny, L = HoughTransform(kapi, thCanny1=100, thCanny2=300, thHough=120)\n",
"imgResult = drawLines(kapi, L)\n",
"print(imgResult.shape)\n",
"print()\n",
"\n",
"# 結果の画像を表示\n",
"displayImage(255 - imgCanny)\n",
"print('↑はCannyフィルタリングの結果(見やすくするため白黒反転してある)')\n",
"print()\n",
"displayImage(imgResult)\n",
"print('↑はハフ変換の結果')"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "YJoXG7rxbtRc",
"colab_type": "code",
"colab": {}
},
"source": [
"# 結果の画像をファイルに書き込む\n",
"cv2.imwrite('result.png', imgResult)\n",
"! ls -l\n",
"# そのファイルをダウンロード\n",
"#files.download('result.png') # この行の先頭の # を削除"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "x7qoXQ21cTVN",
"colab_type": "text"
},
"source": [
"### やってみよう\n",
"\n",
"\n",
"```\n",
"# Hough変換してみる\n",
"imgCanny, L = HoughTransform(kapi, thCanny1=100, thCanny2=300, thHough=120)\n",
" ```\n",
"という行の引数 `thHough` の値を 120 より大きくしたり小さくしたりして,どのような変化があるか観察しよう.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "eI5hA_lLdZVf",
"colab_type": "text"
},
"source": [
"### おまけ課題\n",
"\n",
"**やらなくても減点にはなりません.やったら棒茄子?**\n",
"\n",
"以下のセルのコメントをはずして実行すれば,自分の好きな画像をアップロードできます.その画像に Hough 変換を適用し,結果の画像と考察を takataka に Teams チャットで送ってください.\n",
"\n",
"画像は Hough 変換して楽しそうなものを選ぼう.画像によっては,上記の `thHough` に加えて,`thCanny1` と `thCanny2` の値もいじらないとうまくいかないかもしれません.\n",
"`th1Canny1` < `thCanny2` を保ったまま大きくしたり小さくしたりして試してみてください.\n",
" "
]
},
{
"cell_type": "code",
"metadata": {
"id": "MdriHVkrdW3t",
"colab_type": "code",
"colab": {}
},
"source": [
"# ファイルをアップロード.このセルを実行して「ファイル選択」ボタンを押して...\n",
"#uploaded = files.upload() # この行の先頭の # を消して実行すると,ファイルをアップロードできる\n",
"!ls -l\n",
"#hoge = cv2.imread('アップロードした画像のファイル名')\n",
"# あとは kapi のかわりに hoge を使えば..."
],
"execution_count": null,
"outputs": []
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment