Skip to content

OpenCV チートシート

オープンソースのコンピュータビジョンと機械学習ライブラリ。

01

はじめに

画像の読み取り、表示、保存

OpenCV が画像を(RGB ではなく)BGR の順で読むため — matplotlib や PIL と相互運用するときのよくある落とし穴です。キーが押されるまで止めるのが、cv2.waitKey(0) で、ウィンドウを閉じるには必ず destroyAllWindows() を呼びましょう。JPEG の品質が 0〜100 です。

opencv
import cv2
import numpy as np

# read an image (BGR format by default)
img = cv2.imread("photo.jpg")
print(img.shape)  # (height, width, channels)

# read as grayscale
gray = cv2.imread("photo.jpg", cv2.IMREAD_GRAYSCALE)

# read with alpha channel
rgba = cv2.imread("logo.png", cv2.IMREAD_UNCHANGED)

# display
cv2.imshow("window", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

# save
cv2.imwrite("output.jpg", img, [cv2.IMWRITE_JPEG_QUALITY, 90])

インストールとインポート

主なモジュールだけを ship するのが、opencv-python で、SIFT/SURF や ArUco のような(しばしば特許に絡む)追加モジュールを加えるのが、opencv-contrib-python です。X11 の依存を引き込まないため、サーバー/Docker では headless のバリアントを使いましょう。cv2 という名前にもかかわらず、OpenCV 4.x が依然 cv2 としてインポートされます。

opencv
# Install OpenCV (Python bindings)
pip install opencv-python          # main modules only
pip install opencv-contrib-python  # includes extra modules (SIFT, SURF, aruco...)
pip install opencv-python-headless # no GUI (servers / Docker)

# The universal alias is cv2
import cv2
print(cv2.__version__)             # e.g. 4.9.0

# NumPy is required — images are ndarray
import numpy as np

NumPy 配列としての画像

NumPy 配列であるのが、OpenCV の画像です。そのため、NumPy について知っているすべてが適用されます。座標の慣例が img[y, x](行, 列)であり、(x, y)の画像座標の逆であるため — よくあるバグの源です。BGR のカラー画像が (H, W, 3) で、グレースケールが (H, W) です。

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg")   # BGR uint8, shape (H, W, 3)
print(type(img))                # <class 'numpy.ndarray'>
print(img.shape, img.dtype)     # (480, 640, 3) uint8

# A grayscale image is 2-D: (H, W)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
print(gray.shape)               # (480, 640)

# Coordinate convention: img[y, x]  (row, col)
px = img[100, 200]              # BGR pixel at (x=200, y=100)
blue, green, red = img[100, 200]

# Vectorized access to a region (ROI)
roi = img[50:150, 100:300]      # rows 50-149, cols 100-299

ピクセルへのアクセスと ROI

img[y, x] 経由のピクセルごとのアクセスが遅く、ループでは推奨されないため — 必ず NumPy のスライスを推奨しましょう。後でソースへの変更が混入しないよう、ROI を割り当てるときは .copy() を使いましょう。単一の色チャンネル上で操作する最速の方法が、img[:, :, channel] の修正です。

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg")

# access a single pixel (slow)
b, g, r = img[100, 200]

# access a single channel faster
blue = img[100, 200, 0]
img[100, 200] = [255, 255, 255]   # set to white

# numpy slicing is much faster than item-by-item
roi = img[100:200, 200:400].copy()

# copy ROI to another location
img[0:100, 0:200] = roi

# modify a whole channel
img[:, :, 2] = 0   # zero out the red channel

データ型と変換

uint8(0〜255)を期待するのが、ほとんどの OpenCV の関数ですが、SIFT、オプティカルフロー、エッジ検出のようなアルゴリズムが、しばしば float32 を必要とします。引き算の後の .astype() による直接のキャストは決してしないこと — uint8 のオーバーフローが -1 を 255 に変えます。cv2.absdiff を使うか、先に float へ変換しましょう。cv2.imwrite / imshow の前には、必ず uint8 へ戻しましょう。

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg")      # uint8, 0-255
print(img.dtype, img.min(), img.max())   # uint8 0 255

# convert to float32 (0.0-1.0 for many algorithms)
f = img.astype(np.float32) / 255.0

# convert back to uint8 for display/save
u = (f * 255).astype(np.uint8)

# clamp then cast (avoid overflow when subtracting)
diff = cv2.absdiff(img, img)       # safe subtraction
print(diff.dtype)                  # uint8

# CV_32F / CV_64F / CV_8U constants (used in some functions)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
print(gray.dtype)                  # uint8
02

ビデオのキャプチャ

Web カメラを開く

デフォルトの Web カメラを開くのが、VideoCapture(0) です。追加のカメラには、1、2... を使いましょう。デバイスを解放するため、必ず cap.release() を呼びましょう — 忘れると、カメラが他のアプリにビジネスのまま残り得ます。約 1ms 待つのが、waitKey(1) で、waitKey が 64 ビットのシステムで 8 ビットより多く返すため、& 0xFF のトリックが互換性を確保します。

opencv
import cv2

cap = cv2.VideoCapture(0)           # 0 = default camera
print(cap.isOpened())              # True if camera opened

while True:
    ret, frame = cap.read()        # ret is False at end of stream
    if not ret:
        break

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow("frame", gray)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

動画ファイルの読み取り

一部のコーデックで CAP_PROP_FRAME_COUNT がしばしば概算であり信頼できないため — 正確なシークには頼らないこと。大体正しい速度で再生するのが、waitKey(int(1000/fps)) で、正確なタイミングには本物の時計を使いましょう。適切なバックエンド(FFmpeg)なしでは、一部の圧縮動画が開きません。

opencv
import cv2

cap = cv2.VideoCapture("movie.mp4")

# video properties
fps    = cap.get(cv2.CAP_PROP_FPS)
width  = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
count  = cap.get(cv2.CAP_PROP_FRAME_COUNT)
print(f"{width}x{height} @ {fps} fps, {count} frames")

while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break
    cv2.imshow("video", frame)
    if cv2.waitKey(int(1000 / fps)) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

動画の保存 / 書き込み

プラットフォームとコーデック依存なのが、FourCC コードです:広く移植可能なのが 'mp4v'、.avi を作るのが 'XVID'、H.264 を与えるのが 'avc1' です(独自コーデックなしでは利用不可かも)。VideoWriter へ渡すフレームサイズが、書き込むフレームと MUST で一致しなければならず、さもなければファイルが壊れます。ファイルを流して閉じるには、必ず out.release() を呼びましょう。

opencv
import cv2

cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'mp4v')   # or 'XVID', 'avc1'
fps = 20.0
size = (640, 480)
out = cv2.VideoWriter("out.mp4", fourcc, fps, size)

while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break
    frame = cv2.resize(frame, size)
    out.write(frame)
    cv2.imshow("rec", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
out.release()
cv2.destroyAllWindows()

カメラの設定

ハードウェアとドライバ依存なのが、カメラのプロパティです。多くの Web カメラが、未対応の設定を静かに無視するか最も近い有効な値へスナップするため、本物の値を読み戻すことを必ず行いましょう。log2 の秒を使うのが、CAP_PROP_EXPOSURE です(-4 = 1/16 秒)。ほとんどのカメラで手動露出が効くためには、自動露出を無効化する必要があります(1 へ設定)。

opencv
import cv2

cap = cv2.VideoCapture(0)

# set resolution
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)

# set exposure / focus / brightness
cap.set(cv2.CAP_PROP_EXPOSURE, -4)      # log2 exposure time
cap.set(cv2.CAP_PROP_BRIGHTNESS, 128)
cap.set(cv2.CAP_PROP_AUTO_EXPOSURE, 1)  # 1=manual, 3=auto

# disable autofocus and set manual focus
cap.set(cv2.CAP_PROP_AUTOFOCUS, 0)
cap.set(cv2.CAP_PROP_FOCUS, 50)

print(cap.get(cv2.CAP_PROP_FRAME_WIDTH))   # actual width may differ

フレームレートとタイミング

設定された FPS を返すのが、cap.get(CAP_PROP_FPS) であり、実際のキャプチャレートではありません — 本物の時計で測りましょう。ジッターを平滑化するのが、30 フレームの移動平均です。FPS の最大の殺し手が、cv2.imshow(GUI スレッド)と、フレームごとの cv2.imwrite であるため、ベンチマークでは表示を無効化しましょう。決定的なタイミングのためには、スレッドでフレームを蓄積し、キューから処理しましょう。

opencv
import cv2
import time

cap = cv2.VideoCapture(0)
prev = time.time()
fps_hist = []

while True:
    ret, frame = cap.read()
    if not ret:
        break

    now = time.time()
    dt = now - prev
    prev = now
    if dt > 0:
        fps_hist.append(1.0 / dt)
        fps = sum(fps_hist[-30:]) / min(len(fps_hist), 30)
        cv2.putText(frame, f"FPS: {fps:.1f}", (10, 30),
                    cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)

    cv2.imshow("fps", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()
03

描画

線と長方形

その場で画像を書き換えるのが、すべての描画関数です — 元を保ちたいならコピーを渡しましょう。座標が (x, y) であり、NumPy の [y, x] のインデックスと逆です。色が BGR のタプルです。塗りつぶし形状には thickness=-1 を、斜めの縁の滑らかな(アンチエイリアスされた)線には、cv2.LINE_AA を。

opencv
import cv2
import numpy as np

img = np.zeros((400, 400, 3), dtype=np.uint8)

# line(img, pt1, pt2, color, thickness)
cv2.line(img, (10, 10), (390, 10), (0, 255, 0), 2)

# rectangle(img, pt1, pt2, color, thickness)
cv2.rectangle(img, (50, 50), (200, 150), (255, 0, 0), 3)

# filled rectangle (thickness = -1)
cv2.rectangle(img, (220, 50), (370, 150), (0, 0, 255), -1)

# anti-aliased line (cv2.LINE_AA)
cv2.line(img, (10, 380), (390, 200), (255, 255, 0), 1, cv2.LINE_AA)

cv2.imshow("img", img)
cv2.waitKey(0)

円と楕円

(halfWidth, halfHeight)であるのが、ellipse の axes パラメータです — 全幅が 2 * axes[0] です。楕円全体を回転させるのが、angle で、部分的な弧を描くのが、startAngle/endAngle です(0 度 = 右、反時計回り)。円グラフのスライスや動きの方向のインジケータを描画する標準的な方法が、部分的な弧の描画です。

opencv
import cv2
import numpy as np

img = np.zeros((400, 400, 3), dtype=np.uint8)

# circle(img, center, radius, color, thickness)
cv2.circle(img, (100, 100), 50, (0, 255, 255), 3)
cv2.circle(img, (300, 100), 50, (255, 0, 255), -1)   # filled

# ellipse(img, center, axes, angle, startAngle, endAngle, color, thickness)
cv2.ellipse(img, (200, 250), (100, 50), 30, 0, 360, (0, 255, 0), 2)

# partial arc (0 to 180 degrees)
cv2.ellipse(img, (200, 250), (100, 50), 30, 0, 180, (0, 0, 255), 3)

cv2.imshow("img", img)
cv2.waitKey(0)

多角形と Polylines

点の配列のリストを受け付けるのが、polylines であるため、1 回の呼び出しで複数の多角形が描けます。点の配列は MUST で int32 であり (-1, 1, 2) へリシェイプされなければなりません。塗りつぶし形状には fillPoly を、半透明の塗りには、オーバーレイ上に描き addWeighted でブレンドしましょう。最後の点を最初へ結ぶのが、isClosed フラグです。

opencv
import cv2
import numpy as np

img = np.zeros((400, 400, 3), dtype=np.uint8)

# polygon points: shape (N, 1, 2), int32
pts = np.array([[50, 50], [200, 30], [350, 200],
                [300, 350], [80, 300]], dtype=np.int32)
pts = pts.reshape((-1, 1, 2))

# outline only (not closed)
cv2.polylines(img, [pts], False, (0, 255, 0), 2)

# closed polygon outline
cv2.polylines(img, [pts], True, (255, 0, 0), 3)

# filled polygon
cv2.fillPoly(img, [pts], (0, 0, 255))

cv2.imshow("img", img)
cv2.waitKey(0)

テキスト

Hershey のベクターフォントが、OpenCV の組み込みフォントです — CJK/中国語の文字に対応しません。非ラテンのテキストには、PIL(Pillow)の ImageFont で描画し変換し戻すか、opencv-contrib から cv2.freetype を使いましょう。((width, height), baseline) を返すのが、getTextSize です — テキストの中央寄せや背景ボックスの描画に有用です。

opencv
import cv2
import numpy as np

img = np.zeros((300, 600, 3), dtype=np.uint8)

# putText(img, text, org, fontFace, fontScale, color, thickness)
cv2.putText(img, "Hello OpenCV", (10, 50),
            cv2.FONT_HERSHEY_SIMPLEX, 1.2, (255, 255, 255), 2)

# fonts
fonts = [cv2.FONT_HERSHEY_SIMPLEX, cv2.FONT_HERSHEY_PLAIN,
         cv2.FONT_HERSHEY_DUPLEX, cv2.FONT_HERSHEY_COMPLEX,
         cv2.FONT_HERSHEY_TRIPLEX, cv2.FONT_ITALIC]
for i, f in enumerate(fonts):
    cv2.putText(img, f"font {i}", (10, 100 + i*30), f, 0.8, (0, 255, 0), 1)

# measure text size before drawing
(text_w, text_h), baseline = cv2.getTextSize(
    "Measured", cv2.FONT_HERSHEY_SIMPLEX, 1.0, 2)
cv2.rectangle(img, (10, 260), (10 + text_w, 260 + text_h + baseline),
              (0, 0, 255), 1)

矢印とマーカー

線の長さの分数であるのが、arrowedLine の tipLength であるため、長い矢印が比例的に大きい先端を持ちます — 一貫した矢印の先端サイズを望むなら明示的に設定しましょう。キーとなるポイント(検出された特徴や角など)のハイライトに便利なのが、drawMarker で、X 形状のマーカーを与えるのが、MARKER_TILTED_CROSS です。

opencv
import cv2
import numpy as np

img = np.zeros((400, 400, 3), dtype=np.uint8)

# arrowedLine(img, pt1, pt2, color, thickness, tipLength)
cv2.arrowedLine(img, (50, 50), (350, 50), (0, 255, 0), 2, tipLength=0.05)
cv2.arrowedLine(img, (200, 200), (200, 380), (0, 0, 255), 3, tipLength=0.1)

# drawMarker (cross, tilted cross, circle, square, diamond)
cv2.drawMarker(img, (100, 300), (255, 0, 255),
               markerType=cv2.MARKER_CROSS, markerSize=30, thickness=2)
cv2.drawMarker(img, (300, 300), (255, 255, 0),
               markerType=cv2.MARKER_DIAMOND, markerSize=30, thickness=2)

cv2.imshow("img", img)
cv2.waitKey(0)

オーバーレイと注釈

(コピー上に描き、その後 addWeighted する)オーバーレイの技法が、半透明の塗りを描く標準的な方法です — OpenCV には形状のためのネイティブの alpha がありません。鮮明に留まるよう、ブレンドの後に、必ず solid のテキストを描きましょう。ブレンド前にオーバーレイ上へテキストを描くと、ぼやけます。このパターンが、検出/セグメンテーションの可視化のあらゆる所にあります。

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg")
overlay = img.copy()

# draw a translucent rectangle on the overlay
cv2.rectangle(overlay, (50, 50), (250, 150), (0, 0, 255), -1)
cv2.putText(overlay, "REGION", (60, 110),
            cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)

# blend overlay onto the original (alpha=0.4)
out = cv2.addWeighted(overlay, 0.4, img, 0.6, 0)

cv2.imshow("out", out)
cv2.waitKey(0)
04

画像の算術

加算と減算

255 で飽和するのが、OpenCV の cv2.add です(250 + 10 = 255)。ラップアラウンドするのが、NumPy の + です(uint8 のオーバーフローにより 250 + 10 = 8)。画像には、必ず cv2.add / cv2.subtract を使いましょう — ラップが、見える黒/白のアーティファクトを作ります。背景の減算と動きの検出の頼みの綱が、absdiff です。

opencv
import cv2
import numpy as np

a = cv2.imread("a.jpg")
b = cv2.imread("b.jpg")
b = cv2.resize(b, (a.shape[1], a.shape[0]))   # match sizes

# OpenCV addition: saturated (caps at 255)
add_cv = cv2.add(a, b)

# NumPy addition: wraps around (250 + 10 = 264 -> 8)
add_np = a + b

# subtract (saturated, never goes below 0)
sub = cv2.subtract(a, b)

# absolute difference (handy for motion detection)
diff = cv2.absdiff(a, b)

ブレンドと AddWeighted

両方の画像が同一のサイズと dtype を持つことを要求するのが、addWeighted です — 先に resize しましょう。すべてのピクセルへ定数を加えるのが、gamma 項で、明るさの制御に有用です。2 つの画像の間のクラシックなフェード/クロスディゾルブが、alpha を 0 から 1 へ掃引する addWeighted です。

opencv
import cv2
import numpy as np

a = cv2.imread("a.jpg")
b = cv2.imread("b.jpg")
b = cv2.resize(b, (a.shape[1], a.shape[0]))

# dst = alpha * a + beta * b + gamma
blend = cv2.addWeighted(a, 0.7, b, 0.3, 0)

# brighten by adding a constant (gamma)
bright = cv2.addWeighted(a, 1.0, a, 0.0, 50)

# fade between two images over N steps
for i in range(11):
    alpha = i / 10.0
    frame = cv2.addWeighted(a, alpha, b, 1 - alpha, 0)
    cv2.imshow("fade", frame)
    cv2.waitKey(200)

Bitwise の操作

マスクを適用する標準的な方法が、bitwise の操作です:mask が非ゼロの所でのみ src を dst へコピーするのが、cv2.bitwise_or(src, dst, mask=mask) です。マスクは、非ゼロが「保持」を意味する、シングルチャネルの 8 ビット画像でなければなりません。ROI 抽出と背景置換の基礎です。

opencv
import cv2
import numpy as np

a = np.zeros((200, 200), dtype=np.uint8)
cv2.rectangle(a, (20, 20), (120, 120), 255, -1)

b = np.zeros((200, 200), dtype=np.uint8)
cv2.circle(b, (100, 100), 60, 255, -1)

# bitwise AND / OR / XOR / NOT
and_ = cv2.bitwise_and(a, b)
or_  = cv2.bitwise_or(a, b)
xor  = cv2.bitwise_xor(a, b)
not_ = cv2.bitwise_not(a)

# use a mask to copy only part of an image
mask = np.zeros((200, 200), dtype=np.uint8)
cv2.circle(mask, (100, 100), 50, 255, -1)
src = np.full((200, 200, 3), (0, 255, 0), dtype=np.uint8)
dst = cv2.imread("photo.jpg")
dst = cv2.resize(dst, (200, 200))
result = cv2.bitwise_or(src, dst, mask=mask)

画像の差分とモーション

最も単純な動きの検出器が、フレーム差分です:連続フレームの間の絶対差分のしきい値処理です。カメラが動くと失敗し、遅い動きを無視するため — 本物のシステムには、背景減算(cv2.createBackgroundSubtractorMOG2)かオプティカルフローを使いましょう。ノイズの除去には、形態学的なオープニング、近くの blob のマージには、dilation を。

opencv
import cv2
import numpy as np

prev = cv2.imread("frame1.jpg", cv2.IMREAD_GRAYSCALE)
curr = cv2.imread("frame2.jpg", cv2.IMREAD_GRAYSCALE)

# absolute difference
diff = cv2.absdiff(prev, curr)

# threshold to get a binary motion mask
_, mask = cv2.threshold(diff, 25, 255, cv2.THRESH_BINARY)

# clean up with morphology
kernel = np.ones((5, 5), np.uint8)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
mask = cv2.dilate(mask, kernel, iterations=2)

# find moving contours
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL,
                               cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
    if cv2.contourArea(c) > 500:
        x, y, w, h = cv2.boundingRect(c)
        cv2.rectangle(curr, (x, y), (x+w, y+h), (0, 255, 0), 2)

ROI とマスキング

不規則な領域を抽出する慣用的な方法が、マスク付きの bitwise_and です。より柔軟だが、整形された画像でなくピクセルのフラットな配列を返すのが、真偽値の NumPy インデックス(img[mask])です。再利用する予定の ROI は必ず .copy() しましょう — スライスが、元に別名を付けるビューを返します。

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg")
h, w = img.shape[:2]

# build a mask: white circle on black background
mask = np.zeros((h, w), dtype=np.uint8)
cv2.circle(mask, (w // 2, h // 2), 150, 255, -1)

# keep only the masked region, zero elsewhere
masked = cv2.bitwise_and(img, img, mask=mask)

# extract ROI by bounding box
roi = img[100:300, 200:500].copy()

# put ROI back (or to a different location)
img[0:200, 0:300] = roi

# boolean mask (NumPy) — also works, but converts to 0/255
bool_mask = np.zeros((h, w), dtype=bool)
bool_mask[100:300, 200:500] = True
img_masked = img.copy()
img_masked[~bool_mask] = 0

飽和対ラップ

uint8 のオーバーフローの罠:NumPy がラップし(300 -> 44)、OpenCV が飽和します(300 -> 255)。0〜255 を超え得る任意の算術のためには、cv2.add/subtract を使うか、先に int16/float32 へ昇格させ、後でクリップして戻しましょう。同じパイプラインで cv2 と NumPy の操作を混ぜることが、謎の暗い/明るいピクセルアーティファクトの第 1 の源です。

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg")

# WRONG: NumPy arithmetic wraps around (200 + 100 -> 44)
bad = img + 100

# RIGHT: cv2.add saturates at 255 (200 + 100 -> 255)
good = cv2.add(img, np.full_like(img, 100))

# subtracting a bright image: cv2 clamps to 0
dark = cv2.subtract(img, np.full_like(img, 100))

# manual saturation (equivalent to cv2.add)
manual = np.clip(img.astype(np.int16) + 100, 0, 255).astype(np.uint8)

# mixing cv2 and numpy is a common bug source:
# half = img // 2          # NumPy: fine (no overflow)
# half_then_add = half + half   # might equal original (ok)
# but bright = img + img  # wraps! 150+150=300 -> 44
05

幾何変換

Resize / Scale

縮小に最良なのが、INTER_AREA です(エイリアシングを避けます)、拡大には INTER_CUBIC か INTER_LINEAR です。最も速いがブロック状なのが、INTER_NEAREST で — 新しいピクセル値を導入してはならないラベル/マスク画像に使われます。(width, height) であるのが、dsize のタプルで、(height, width) である img.shape の逆です。

opencv
import cv2

img = cv2.imread("photo.jpg")
h, w = img.shape[:2]

# resize to a fixed size
small = cv2.resize(img, (320, 240))

# resize by a scale factor (fx, fy)
big = cv2.resize(img, None, fx=2.0, fy=2.0)

# resize keeping aspect ratio
scale = 0.5
new = cv2.resize(img, (int(w * scale), int(h * scale)))

# interpolation methods
down = cv2.resize(img, (w // 2, h // 2),
                  interpolation=cv2.INTER_AREA)      # shrinking
up   = cv2.resize(img, (w * 2, h * 2),
                  interpolation=cv2.INTER_CUBIC)     # enlarging

回転

90 度の倍数には、warpAffine よりはるかに速いのが、cv2.rotate です。度であるのが、getRotationMatrix2D の angle で、正が反時計回りです。クリップなしで回転するには、バウンディングボックス(new_w, new_h)を再計算し回転行列を動かしましょう — さもないと回転された大きな画像の角が切り取られます。

opencv
import cv2

img = cv2.imread("photo.jpg")
h, w = img.shape[:2]

# rotate 90/180/270 (fast, no interpolation)
rot90  = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
rot180 = cv2.rotate(img, cv2.ROTATE_180)
rot270 = cv2.rotate(img, cv2.ROTATE_90_COUNTERCLOCKWISE)

# arbitrary-angle rotation
center = (w // 2, h // 2)
angle = 45
scale = 1.0
M = cv2.getRotationMatrix2D(center, angle, scale)
rot = cv2.warpAffine(img, M, (w, h))

# rotate and expand the canvas to fit the whole image
cos = abs(M[0, 0]); sin = abs(M[0, 1])
new_w = int(h * sin + w * cos)
new_h = int(h * cos + w * sin)
M[0, 2] += (new_w - w) / 2
M[1, 2] += (new_h - h) / 2
rot_fit = cv2.warpAffine(img, M, (new_w, new_h))

Affine 変換

平行性と距離の比を保つのが、affine 変換で — 3 つの点の対応(6 自由度)により定義されます。逆引き経由で暗黙に順方向のマッピングを使うのが、warpAffine です。そのため、M が src→dst をマッピングするが、関数が内部で反転します。境界外の領域の満たされ方を制御するのが、borderMode=BORDER_REFLECT か BORDER_CONSTANT です。

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg")
h, w = img.shape[:2]

# affine: parallel lines stay parallel (6 DOF)
src = np.float32([[50, 50], [200, 50], [50, 200]])
dst = np.float32([[10, 100], [200, 50], [100, 250]])
M = cv2.getAffineTransform(src, dst)
warped = cv2.warpAffine(img, M, (w, h))

# inverse mapping (destination -> source)
inv = cv2.invertAffineTransform(M)

# translation is a special affine
T = np.float32([[1, 0, 100], [0, 1, 50]])  # shift right 100, down 50
shifted = cv2.warpAffine(img, T, (w, h))

# black border is default; use borderMode for other fill
reflected = cv2.warpAffine(img, T, (w, h),
                           borderMode=cv2.BORDER_REFLECT)

Perspective 変換

4 つの非共線の点のペアにより定義されるのが、perspective(homography)です — 8 自由度です。これが標準の「文書スキャナ」変換です:写真の中のカード/紙の 4 つの角を選び、長方形へ warp します。正確に 4 点を必要とするのが、getPerspectiveTransform で、過剰決定の適合には、RANSAC 付きの cv2.findHomography を使いましょう。

opencv
import cv2
import numpy as np

img = cv2.imread("card.jpg")
h, w = img.shape[:2]

# 4 point correspondences define a perspective (homography)
src = np.float32([[73, 110], [320, 78], [380, 350], [40, 320]])
dst = np.float32([[0, 0], [w, 0], [w, h], [0, h]])

M = cv2.getPerspectiveTransform(src, dst)
warped = cv2.warpPerspective(img, M, (w, h))

# invert the homography to map back
M_inv = cv2.getPerspectiveTransform(dst, src)
restored = cv2.warpPerspective(warped, M_inv, (w, h))

Flip とミラー

安価なメモリ内の操作であるのが、flip です — warpAffine よりはるかに速いです。flipCode の符号の慣例:正が水平、0 が垂直、負が両方です。軸を交換するのが、cv2.transpose で、flip と組み合わせると、時々速い 90 度の回転として使われます。

opencv
import cv2

img = cv2.imread("photo.jpg")

# flip(img, flipCode)
#   0  -> vertical flip (around x-axis)  (upside-down)
#   1  -> horizontal flip (around y-axis) (mirror)
#  -1  -> both (180° rotation equivalent)
v = cv2.flip(img, 0)
h = cv2.flip(img, 1)
both = cv2.flip(img, -1)

# transpose (swap x and y axes) — like a 90° rotation + flip
t = cv2.transpose(img)

Remap(カスタムマッピング)

最も一般的な幾何変換が、remap です — resize、回転、そして樽/レンズの歪みの補正さえ、remap として表現できます。Python のループでなく、必ず NumPy のベクトル化でマップを構築しましょう(上のループの版は説明用のみ — 約 100 倍遅いです)。デフォルトが、INTER_LINEAR で、縁でのサブピクセル精度には、INTER_CUBIC を。

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg")
h, w = img.shape[:2]

# build coordinate maps: map_x, map_y say where each output pixel comes from
map_x = np.zeros((h, w), dtype=np.float32)
map_y = np.zeros((h, w), dtype=np.float32)

for y in range(h):
    for x in range(w):
        # mirror the image
        map_x[y, x] = w - 1 - x
        map_y[y, x] = y

remapped = cv2.remap(img, map_x, map_y, cv2.INTER_LINEAR)

# vectorized version (much faster) — wave distortion
xs, ys = np.meshgrid(np.arange(w), np.arange(h))
map_x = xs.astype(np.float32) + 10 * np.sin(ys / 20.0)
map_y = ys.astype(np.float32) + 10 * np.cos(xs / 20.0)
wave = cv2.remap(img, map_x, map_y, cv2.INTER_LINEAR,
                 borderMode=cv2.BORDER_REFLECT)
06

画像のフィルタリング

平均ブラー(ボックスフィルタ)

最も単純なローパスフィルタが、平均ブラーです — 各ピクセルをその近傍の平均に置き換えます。奇数かつ正でなければならないのが、カーネルです。より大きいカーネルがより多くぼかすが、詳細もより速く破壊します。一様な重み付けを特に欲しいときに使いましょう。自然画像には、ガウシアンブラーがほとんど常に良い選択です。

opencv
import cv2

img = cv2.imread("photo.jpg")

# 3x3 box blur
blur3 = cv2.blur(img, (3, 3))

# larger kernel = more blur
blur9 = cv2.blur(img, (9, 9))

# boxFilter with normalized=False gives the sum (not average)
sum_ = cv2.boxFilter(img, -1, (5, 5), normalize=False)

# normalized=True is equivalent to cv2.blur
avg = cv2.boxFilter(img, -1, (5, 5), normalize=True)

ガウシアンブラー

デフォルトの平滑化のカーネルが、ガウシアンブラーです — ガウシアンにより近傍を重み付けし、ボックスフィルタより縁をよく保ちます。ksize=(0,0) と sigmaX を渡せば、OpenCV がカーネルサイズを自動計算します。ノイズの増幅を抑制するため、Canny、ダウンサンプリング、Laplacian の前の必須の前ステップが、ガウシアンブラーです。

opencv
import cv2

img = cv2.imread("photo.jpg")

# GaussianBlur(img, ksize, sigmaX)
g = cv2.GaussianBlur(img, (5, 5), 0)

# specifying sigma explicitly
g2 = cv2.GaussianBlur(img, (5, 5), sigmaX=1.5, sigmaY=1.5)

# odd kernel size required; (0, 0) auto-derives sigma from ksize
g3 = cv2.GaussianBlur(img, (0, 0), sigmaX=2.0)

# Gaussian is the standard pre-processing step before edge detection
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edges = cv2.Canny(blurred, 50, 150)

メディアンブラー

塩胡椒(インパルス)ノイズの頼みの綱が、メディアンブラーです — 各ピクセルを近傍の中央値に置き換えるため、孤立したはずれ値が広がるのでなく取り除かれます。ガウシアンと違い、縁をよく保ちます。奇数でなければならないのが、カーネルサイズです。ソートが絡むため、ガウシアン/ボックスより遅いです。

opencv
import cv2

img = cv2.imread("noisy.jpg")

# median blur — great for salt-and-pepper noise
m = cv2.medianBlur(img, 5)

# larger kernel removes more noise but blurs edges
m2 = cv2.medianBlur(img, 7)

# compared to Gaussian on the same image
g = cv2.GaussianBlur(img, (5, 5), 0)

バイラテラルフィルタ

シャープな縁を保ちつつ、フラットな領域を平滑化するのが、バイラテラルフィルタリングです。空間の近さと色の類似性の両方で近傍を重み付けする、非線形で縁を保つフィルタです。ガウシアンよりはるかに遅い(しばしば 10 倍)です。繰り返し適用が、クラシックな「カートゥーン化」の前処理ステップで、大きい sigmaColor の値が、より多くの色をまたいで混ぜ合わせます。

opencv
import cv2

img = cv2.imread("photo.jpg")

# bilateralFilter(img, d, sigmaColor, sigmaSpace)
#   d            = neighborhood diameter
#   sigmaColor   = how much colors can differ and still blend
#   sigmaSpace   = how far pixels influence each other (spatial)
b = cv2.bilateralFilter(img, d=9, sigmaColor=75, sigmaSpace=75)

# strong edge-preserving smoothing (cartoon effect)
b_strong = cv2.bilateralFilter(img, d=15, sigmaColor=150, sigmaSpace=150)

# repeat several times for a "cartoon / oil painting" look
cartoon = img.copy()
for _ in range(7):
    cartoon = cv2.bilateralFilter(cartoon, d=9, sigmaColor=75, sigmaSpace=75)

シャープニング(カーネル)

高周波を強調するのが、シャープニングのカーネルですが — ノイズも増幅するため、ノイズ除去の後に適用しましょう。合計が 1(明るさを保つ)であるのが、クラシックな 3x3 のシャープニングカーネルで、>1 が明るくします。より制御可能であり、ほとんどの写真エディタが実際に使うのが、(ぼやけたコピーを引き算する)アンシャープマスクの技法です。

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg")

# sharpening kernel: center boosts, neighbors subtracted
kernel = np.array([[ 0, -1,  0],
                   [-1,  5, -1],
                   [ 0, -1,  0]], dtype=np.float32)

sharp = cv2.filter2D(img, -1, kernel)

# stronger sharpening
kernel_strong = np.array([[-1, -1, -1],
                          [-1,  9, -1],
                          [-1, -1, -1]], dtype=np.float32)
sharp2 = cv2.filter2D(img, -1, kernel_strong)

# unsharp mask: image + (image - blurred) * amount
blur = cv2.GaussianBlur(img, (0, 0), 3)
unsharp = cv2.addWeighted(img, 1.5, blur, -0.5, 0)

カスタムカーネル(filter2D)

任意の相関カーネルを適用するのが、filter2D です — ソースの深さを保つのが、ddepth=-1 です。負の係数のためにカーネルは float にでき、結果が負になるなら、ddepth=cv2.CV_16S か CV_32F に切り替え、その後 convertScaleAbs で戻しましょう。(1D カーネルの外積である)分離可能なカーネルは、sepFilter2D 経由で、はるかに速いです。

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg")

# emboss kernel
emboss = np.array([[-2, -1,  0],
                   [-1,  1,  1],
                   [ 0,  1,  2]], dtype=np.float32)
out = cv2.filter2D(img, -1, emboss)

# edge enhance (Laplacian-like)
edge = np.array([[ 0,  1,  0],
                 [ 1, -4,  1],
                 [ 0,  1,  0]], dtype=np.float32)
edges = cv2.filter2D(img, -1, edge)

# box blur done manually
box = np.ones((5, 5), dtype=np.float32) / 25.0
blurred = cv2.filter2D(img, -1, box)

# separable filter (Gaussian) — faster than 2D
kx = cv2.getGaussianKernel(5, 1.0)         # 5x1
ky = cv2.getGaussianKernel(5, 1.0)         # 5x1
g2d = kx @ ky.T                            # 5x5
out2 = cv2.filter2D(img, -1, g2d)
07

形態学的操作

エロージョンとディレーション

前景(白)の領域を縮め小さなノイズの点を取り除くのが、エロージョンで、成長させ小さな穴を満たすのが、ディレーションです。効くのが、カーネルの形状です:一般には RECT、丸い特徴には ELLIPSE、軸に沿った薄化・接続には CROSS です。操作を N 回繰り返すのが、iterations=N で、より大きいカーネルの使用と等価です。

opencv
import cv2
import numpy as np

img = cv2.imread("shape.png", cv2.IMREAD_GRAYSCALE)
_, binary = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

kernel = np.ones((5, 5), np.uint8)

# erosion: shrinks white regions (removes small noise)
eroded = cv2.erode(binary, kernel, iterations=1)

# dilation: grows white regions (fills small holes)
dilated = cv2.dilate(binary, kernel, iterations=1)

# custom kernel shapes
rect = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
cross = cv2.getStructuringElement(cv2.MORPH_CROSS, (5, 5))
ellipse = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))

オープニングとクロージング

より大きいオブジェクトのサイズを変えずに、小さな明るい点を取り除くのが、オープニング(erode→dilate)です。小さな暗い穴を満たすのが、クロージング(dilate→erode)です。冪等です — 2 回の適用が 1 回と同じです。両方の種類の欠陥を扱うクラシックなノイズ除去のパターンが、close-then-open(または open-then-close)です。

opencv
import cv2
import numpy as np

img = cv2.imread("noisy.png", cv2.IMREAD_GRAYSCALE)
_, binary = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

kernel = np.ones((5, 5), np.uint8)

# opening = erode then dilate -> removes small foreground noise
opened = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel)

# closing = dilate then erode -> fills small holes in foreground
closed = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel)

# typical denoise pipeline: open then close
clean = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel)
clean = cv2.morphologyEx(clean, cv2.MORPH_OPEN, kernel)

形態学的グラデーション

オブジェクトの境界の太い輪郭を作るのが、形態学的グラデーション(dilation - erosion)です — 素早いエッジ検出器やセグメンテーションのためのマスクとして有用です。Canny と違い、満たされた幅広い縁を与えるため、正確な縁位置の測定よりも、領域のハイライトに向いています。

opencv
import cv2
import numpy as np

img = cv2.imread("shape.png", cv2.IMREAD_GRAYSCALE)
_, binary = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

kernel = np.ones((5, 5), np.uint8)

# gradient = dilation - erosion -> outlines of objects
gradient = cv2.morphologyEx(binary, cv2.MORPH_GRADIENT, kernel)

# on a grayscale image (works too)
gray_grad = cv2.morphologyEx(img, cv2.MORPH_GRADIENT, kernel)

Top Hat と Black Hat

カーネルより小さい小さな明るい構造を取り出すのが、Top-hat です(暗い文書上のテキストなど)、小さな暗い構造を取り出すのが、black-hat です。影/ハイライトの抽出と、速い不均一照明の補正器に(文書スキャナで一般的な、背景による除算のトリック)、一緒に使われます。

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg", cv2.IMREAD_GRAYSCALE)

kernel = np.ones((15, 15), np.uint8)

# top hat = image - opening -> small bright features on dark bg
tophat = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel)

# black hat = closing - image -> small dark features on bright bg
blackhat = cv2.morphologyEx(img, cv2.MORPH_BLACKHAT, kernel)

# use case: correct uneven illumination
# background = large closing; divide image by background
bg = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
corrected = cv2.divide(img, bg, scale=255)

骨格化

二値形状を 1 ピクセル幅の中央軸へ薄くするのが、形態学的な骨格化です — OCR、指紋、血管の分析に有用です。画像が空になるまで動くのが、反復する erode-subtract-open のループです。本番での使用には、より速くきれいな結果を与える、scikit-image の medial_axis や thinning を。

opencv
import cv2
import numpy as np

img = cv2.imread("shape.png", cv2.IMREAD_GRAYSCALE)
_, img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

# skeleton via iterative morphological opening
kernel = np.ones((3, 3), np.uint8)
skeleton = np.zeros_like(img)

while True:
    eroded = cv2.erode(img, kernel)
    opened = cv2.morphologyEx(eroded, cv2.MORPH_OPEN, kernel)
    temp = cv2.subtract(eroded, opened)
    skeleton = cv2.bitwise_or(skeleton, temp)
    img = eroded
    if cv2.countNonZero(img) == 0:
        break

Hit-or-Miss

形態学のパターンマッチャーが、hit-or-miss です — 前景と背景のピクセルの正確な構成を見つけるため、角や T 字路のような特定の形状の検出に有用です。必須の前景に 1 を、必須の背景に -1 を、考慮しないに 0 を使うのが、カーネルです。ニッチですが、正確なパターンの位置特定には無敵です。

opencv
import cv2
import numpy as np

img = cv2.imread("pattern.png", cv2.IMREAD_GRAYSCALE)
_, binary = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

# hit-or-miss finds exact patterns
# kernel encodes foreground (1), background (-1), don't-care (0)
kernel = np.array([[ 0,  1, -1],
                   [ 1, -1, -1],
                   [ 1,  1,  0]], dtype=np.int32)

hits = cv2.morphologyEx(binary, cv2.MORPH_HITMISS, kernel)

# count matching locations
ys, xs = np.where(hits > 0)
print(f"found {len(xs)} matches")
08

エッジ検出

Canny エッジ検出器

最もよく使われるエッジ検出器が、Canny です:ガウシアンの平滑化 → Sobel の勾配 → 非最大抑制 → ヒステリシス(2 つのしきい値)。高いしきい値を超えるピクセルがエッジであり、低と高の間のピクセルが、強いエッジに接続しているときだけエッジです。多様な画像で良く機能するのが、(中央値 × 0.7/1.3 の)自動しきい値のトリックです。

opencv
import cv2

img = cv2.imread("photo.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)

# Canny(image, threshold1, threshold2, apertureSize, L2gradient)
edges = cv2.Canny(blurred, 50, 150)

# auto-tuned thresholds from the median intensity
v = np.median(blurred)
lower = int(max(0, 0.7 * v))
upper = int(min(255, 1.3 * v))
auto = cv2.Canny(blurred, lower, upper)

# L2 gradient (more accurate, slower)
edges_l2 = cv2.Canny(blurred, 50, 150, L2gradient=True)

Sobel 演算子

1 階微分を計算するのが、Sobel です — 負の勾配を捉えるため、ddepth=cv2.CV_64F(か CV_16S)を使いましょう。さもなければ、uint8 のオーバーフローにより、暗から明への遷移が見えなくなります。標準が ksize=3 で、より滑らかだが幅広の縁を与えるのが、ksize=5 です。Canny と多くの特徴検出器の基礎が、(sqrt(sx²+sy²) の)大きさです。

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg", cv2.IMREAD_GRAYSCALE)

# Sobel x (vertical edges)
sx = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=3)

# Sobel y (horizontal edges)
sy = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=3)

# gradient magnitude
mag = np.sqrt(sx**2 + sy**2)
mag = np.uint8(255 * mag / mag.max())

# gradient direction (for non-max suppression)
angle = np.arctan2(sy, sx)

# convert back to visible uint8
sx_abs = cv2.convertScaleAbs(sx)
sy_abs = cv2.convertScaleAbs(sy)

Laplacian

2 階微分であるのが、Laplacian で — ノイズに非常に敏感であるため、必ず先にブラーしましょう。ゼロ交差(符号の変化)を検出し、細く正確な縁を与えますが方向はありません。最もよく使われるのが、Marr-Hildreth のエッジ検出と、画像のシャープニング(アンシャープマスク)での「L」チャンネルの入力です。2 階微分が強く負に振れるため、CV_64F を。

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg", cv2.IMREAD_GRAYSCALE)
blurred = cv2.GaussianBlur(img, (3, 3), 0)

# Laplacian: second derivative in both directions
lap = cv2.Laplacian(blurred, cv2.CV_64F)
lap_abs = cv2.convertScaleAbs(lap)

# zero-crossing detection (sharper edges)
# Manual Laplacian kernel
kernel = np.array([[0,  1, 0],
                   [1, -4, 1],
                   [0,  1, 0]], dtype=np.float32)
edges = cv2.filter2D(blurred, -1, kernel)

Scharr フィルタ

3x3 の窓向けに設計された Sobel のバリアントが、Scharr です — 小さいカーネルを使わなければならないとき、Sobel ksize=3 より正確な勾配の方向を与えます。大きいカーネル(5x5、7x7)では、Sobel で十分です。ksize=-1 付きの cv2.Sobel が、Scharr と等価です。勾配の方向が効くとき(HOG、縁の向き)に推奨されるのが、Scharr です。

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg", cv2.IMREAD_GRAYSCALE)

# Scharr: a Sobel variant optimized for 3x3 kernels
# better rotational symmetry than 3x3 Sobel
sx = cv2.Scharr(img, cv2.CV_64F, 1, 0)
sy = cv2.Scharr(img, cv2.CV_64F, 0, 1)

mag = cv2.magnitude(sx, sy)
mag_u8 = cv2.convertScaleAbs(mag)

# equivalent to Sobel with ksize=-1
sx2 = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=-1)

エッジ検出のパイプライン

実用的なエッジのタスクの大きな割合をカバーするのが、グレースケール → ノイズ除去 → Canny → dilate → findContours のパイプラインです。さもなければ 1 つのオブジェクトが多くに分割され得る壊れた縁を閉じるのが、輪郭発見前の dilation です。エンジニアリングの労力のほとんどが行くのが、Canny のしきい値とノイズ除去カーネルのサイズの調整です。

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg")

# 1. grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 2. denoise (Gaussian or bilateral)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)

# 3. auto-thresholded Canny
v = np.median(blurred)
edges = cv2.Canny(blurred, int(0.7 * v), int(1.3 * v))

# 4. dilate to close gaps, then find contours
edges = cv2.dilate(edges, np.ones((3, 3), np.uint8), iterations=1)
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL,
                               cv2.CHAIN_APPROX_SIMPLE)

# 5. filter by area
out = img.copy()
for c in contours:
    if cv2.contourArea(c) > 100:
        cv2.drawContours(out, [c], -1, (0, 255, 0), 2)

cv2.imshow("edges", edges)
cv2.imshow("contours", out)
cv2.waitKey(0)
09

輪郭

輪郭の検出

OpenCV 3.x では、findContours がソース画像を書き換えるため — 後で二値が必要なら、コピーを渡しましょう。最も外側の輪郭だけを返す(最速)のが、RETR_EXTERNAL で、ネストした形状(オブジェクトの中の穴)のための完全な階層を与えるのが、RETR_TREE です。まっすぐな線に沿った冗長な点を破棄しメモリを節約するのが、CHAIN_APPROX_SIMPLE です。

opencv
import cv2

img = cv2.imread("shapes.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

# findContours(image, mode, method)
# mode: RETR_EXTERNAL (outer only), RETR_LIST, RETR_TREE, RETR_CCOMP
# method: CHAIN_APPROX_SIMPLE compresses horizontal/vertical/diagonal segments
contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL,
                                       cv2.CHAIN_APPROX_SIMPLE)

print(f"found {len(contours)} contours")
# hierarchy is shape (1, N, 4): [next, prev, child, parent]

# OpenCV 3 returns (image, contours, hierarchy)
# OpenCV 4 returns (contours, hierarchy)

輪郭の描画

drawContours(image, contours, contourIdx, color, thickness):contourIdx=-1 がすべてを描き、特定のインデックスが 1 つを描きます。輪郭を満たすのが、thickness=-1 です。平均色やマスクされたヒストグラムのような、下流の操作のための輪郭マスクを構築する標準的な方法が、白紙の画像上への描画です。

opencv
import cv2

img = cv2.imread("shapes.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL,
                               cv2.CHAIN_APPROX_SIMPLE)

# draw all contours (-1), color, thickness
cv2.drawContours(img, contours, -1, (0, 255, 0), 2)

# draw a single contour by index
cv2.drawContours(img, contours, 0, (0, 0, 255), 3)

# filled contour (thickness = -1)
cv2.drawContours(img, contours, -1, (255, 0, 0), -1)

# draw on a blank canvas (mask)
mask = np.zeros_like(gray)
cv2.drawContours(mask, contours, -1, 255, -1)

輪郭の特性

ピクセルであるのが、contourArea で、穴を無視します(正味の面積のためには、RETR_CCOMP の階層付きの輪郭を使いましょう)。中心(m10/m00、m01/m00)を与えるのが、moments の辞書です — m00 が 0 なら(退化した輪郭)、ゼロ除算を守りましょう。形状分類のための最も単純な形状の記述子が、アスペクト比と extent です。

opencv
import cv2

img = cv2.imread("shapes.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL,
                               cv2.CHAIN_APPROX_SIMPLE)

for c in contours:
    area = cv2.contourArea(c)             # area in pixels
    peri = cv2.arcLength(c, True)         # perimeter (closed=True)
    M = cv2.moments(c)                     # spatial moments
    cx = int(M['m10'] / M['m00'])          # centroid x
    cy = int(M['m01'] / M['m00'])          # centroid y

    # bounding box
    x, y, w, h = cv2.boundingRect(c)
    aspect = w / float(h)                 # aspect ratio
    extent = area / float(w * h)          # filled area ratio

    print(f"area={area:.0f} peri={peri:.1f} center=({cx},{cy}) aspect={aspect:.2f}")

バウンディング矩形

軸整列のボックスを与えるのが(速く、単純)、boundingRect で、最も小さい回転された矩形を与えるのが、minAreaRect です(オブジェクトの本物の向き/サイズの測定に有用)。drawContours へ渡せる 4 つの角の点へ、回転された rect を変換するのが、boxPoints です。輪郭を含む最も小さい円が、minEnclosingCircle です。

opencv
import cv2

img = cv2.imread("shapes.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL,
                               cv2.CHAIN_APPROX_SIMPLE)

for c in contours:
    # axis-aligned bounding rectangle
    x, y, w, h = cv2.boundingRect(c)
    cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)

    # minimum area (rotated) rectangle
    rect = cv2.minAreaRect(c)             # ((cx, cy), (w, h), angle)
    box = cv2.boxPoints(rect)             # 4 corner points
    box = np.int0(box)
    cv2.drawContours(img, [box], 0, (0, 0, 255), 2)

    # minimum enclosing circle
    (cx, cy), r = cv2.minEnclosingCircle(c)
    cv2.circle(img, (int(cx), int(cy)), int(r), (255, 0, 0), 2)

輪郭の近似

Douglas-Peucker のアルゴリズムを使い、より少ない頂点の多角形へ輪郭を単純化するのが、approxPolyDP です。許容を制御するのが、epsilon です(通常、周囲の 1〜5%)— 小さいほどより多くの詳細が保たれます。頂点数のカウントが、クラシックな手作りの形状分類器です — 三角形 = 3、長方形 = 4、円 = 多く。

opencv
import cv2

img = cv2.imread("shapes.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL,
                               cv2.CHAIN_APPROX_SIMPLE)

for c in contours:
    peri = cv2.arcLength(c, True)
    # approxPolyDP: simplify the contour to fewer vertices
    eps = 0.04 * peri                      # 4% of perimeter
    approx = cv2.approxPolyDP(c, eps, True)

    n = len(approx)
    if n == 3:
        label = "triangle"
    elif n == 4:
        label = "rectangle"
    elif n == 5:
        label = "pentagon"
    else:
        label = f"{n}-gon"

    cv2.drawContours(img, [approx], -1, (0, 255, 0), 2)
    cv2.putText(img, label, tuple(approx[0][0]),
                cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)

凸包と Defects

輪郭を囲む最も小さい凸形状が、凸包です — オブジェクトのコンパクトさの測定と、凸性 defects 経由の手/指の検出に有用です。輪郭が hull に対しどれほど「内側へ」沈むかを測るのが、各 defect の深さです。手のシルエット上の深い defect が、典型的には指の間の隙間に対応します。

opencv
import cv2

img = cv2.imread("hand.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL,
                               cv2.CHAIN_APPROX_SIMPLE)
c = max(contours, key=cv2.contourArea)

# convex hull (smallest convex polygon enclosing the contour)
hull = cv2.convexHull(c)
cv2.drawContours(img, [hull], -1, (0, 255, 0), 2)

# convexity defects (gaps between contour and hull) — needs returnPoints=False
hull_idx = cv2.convexHull(c, returnPoints=False)
defects = cv2.convexityDefects(c, hull_idx)
# defects[i] = (start, end, far, depth) — depth in 1/256 of peri

# is the contour convex?
is_convex = cv2.isContourConvex(c)
10

しきい値処理

基本のしきい値

THRESH_BINARY:超える→255、下回る→0 です。THRESH_TRUNC:超える→thresh で上限、下回る→変わらず。THRESH_TOZERO:超える→変わらず、下回る→0 です。素のしきい値処理では、返される ret が入力のしきい値と等しく、Otsu/Triangle では意味を持つようになります。範囲外のピクセルの扱い方で、タイプを選びましょう。

opencv
import cv2

img = cv2.imread("doc.png", cv2.IMREAD_GRAYSCALE)

# threshold(src, thresh, maxval, type)
# returns (retval, binary_image)
ret, binary = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

# threshold types
_, inv     = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV)
_, trunc   = cv2.threshold(img, 127, 255, cv2.THRESH_TRUNC)
_, tozero  = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO)
_, tozero_inv = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO_INV)

# ret is the threshold actually used (useful with Otsu)

Adaptive しきい値

局所的な近傍に基づきピクセルごとに異なるしきい値を計算するのが、adaptive しきい値処理です — 不均一な照明の画像(文書の写真など)には不可欠です。奇数でなければならず(通常 11〜31)特徴サイズより大きくなければならないのが、blockSize です。局所平均から定数を引き算するのが、C で、低コントラストのノイズを抑制するため引き上げましょう。

opencv
import cv2

img = cv2.imread("doc.png", cv2.IMREAD_GRAYSCALE)
img = cv2.medianBlur(img, 5)

# adaptiveThreshold(src, maxValue, adaptiveMethod, thresholdType, blockSize, C)
# adaptiveMethod:
#   ADAPTIVE_THRESH_MEAN_C  -> mean of neighborhood minus C
#   ADAPTIVE_THRESH_GAUSSIAN_C -> weighted mean minus C
adap_mean = cv2.adaptiveThreshold(img, 255,
    cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)

adap_gauss = cv2.adaptiveThreshold(img, 255,
    cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)

Otsu の方法

前景と背景のクラスの間の分散を最大化することで、最適なグローバルしきい値を見つけるのが、Otsu の方法です — thresh=0 を渡し、THRESH_OTSU のフラグを加えましょう。必ず先にブラーしましょう。ヒストグラムのノイズに敏感なのが、Otsu です。単一の支配的なピークを持つ画像(顕微鏡など)では、Triangle の方法が良く機能します。計算されたしきい値が、返される ret です。

opencv
import cv2

img = cv2.imread("doc.png", cv2.IMREAD_GRAYSCALE)
blurred = cv2.GaussianBlur(img, (5, 5), 0)

# Otsu: automatically picks the threshold that maximizes between-class variance
ret, otsu = cv2.threshold(blurred, 0, 255,
                          cv2.THRESH_BINARY + cv2.THRESH_OTSU)
print(f"Otsu threshold: {ret}")

# Triangle method (good for skewed histograms / single peak)
ret_t, tri = cv2.threshold(blurred, 0, 255,
                           cv2.THRESH_BINARY + cv2.THRESH_TRIANGLE)
print(f"Triangle threshold: {ret_t}")

色のしきい値(inRange)

標準の色セグメンテーションの道具が、inRange です — 先に HSV へ変換しましょう。色相(hue)を明るさから分離し、しきい値が照明の変化に頑健になるからです。赤の hue が 0/180 の周りをラップするため、2 つのマスクが OR され必要です。マスクの中のノイズの点を減らすため、inRange の前には必ずブラーしましょう。

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg")
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

# detect a range of green pixels
lower = np.array([35, 50, 50])
upper = np.array([85, 255, 255])
mask = cv2.inRange(hsv, lower, upper)

# apply mask to the original
result = cv2.bitwise_and(img, img, mask=mask)

# hue wraps around for red (0-10 and 170-180)
mask1 = cv2.inRange(hsv, np.array([0, 50, 50]),   np.array([10, 255, 255]))
mask2 = cv2.inRange(hsv, np.array([170, 50, 50]), np.array([180, 255, 255]))
red_mask = cv2.bitwise_or(mask1, mask2)

しきい値のパイプライン

ほとんどの二値化のタスクを扱うのが、ノイズ除去 → しきい値 → 形態学のパイプラインです。均一な照明には Otsu を、不均一には adaptive を選びましょう。内部の穴と外部の点の両方を取り除くのが、形態学的な close-then-open です。二値マスクは必ず検査しましょう — しきい値のパラメータが、ほとんど常に画像固有であり、dataset ごとの調整が必要です。

opencv
import cv2
import numpy as np

img = cv2.imread("doc.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 1. denoise
blurred = cv2.GaussianBlur(gray, (5, 5), 0)

# 2. choose a method
#    - flat lighting    -> Otsu
#    - uneven lighting  -> adaptive
#    - document scan    -> adaptive Gaussian
if lighting == "flat":
    _, binary = cv2.threshold(blurred, 0, 255,
                              cv2.THRESH_BINARY + cv2.THRESH_OTSU)
else:
    binary = cv2.adaptiveThreshold(blurred, 255,
        cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 21, 5)

# 3. morphology cleanup
kernel = np.ones((3, 3), np.uint8)
binary = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel)
binary = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel)

OCR のための二値化

OCR には、不均一な照明のため、写真化された文書で、adaptive ガウシアンがほとんど常にグローバルな Otsu に勝ちます。文字の高さに blockSize を合わせましょう(経験則:線の幅 × 4 の 1〜2 倍)。黒い背景上の白いテキストを好むのが、ほとんどの OCR エンジン(Tesseract)です。あなたの二値が逆なら反転しましょう。

opencv
import cv2

img = cv2.imread("text.png", cv2.IMREAD_GRAYSCALE)

# adaptive Gaussian with a block size matched to character height
# (e.g. char ~25 px -> blockSize ~31)
binary = cv2.adaptiveThreshold(img, 255,
    cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 10)

# invert if needed (OCR often prefers black-on-white)
binary_inv = cv2.bitwise_not(binary)

# Otsu on a preprocessed image as an alternative
blur = cv2.GaussianBlur(img, (3, 3), 0)
_, otsu = cv2.threshold(blur, 0, 255,
                        cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
11

色空間

BGR / RGB / Gray

デフォルトで BGR として画像を読むのが、OpenCV で、RGB を使うのが、ほとんどの他のライブラリ(matplotlib、PIL、scikit-image)です。「赤と青が入れ替わった」画像の最もよくある原因が、cvtColor の忘れです。知覚的な重み(Y = 0.299R + 0.587G + 0.114B)を使うのが、グレースケールの変換で、単純な平均ではありません。

opencv
import cv2

bgr = cv2.imread("photo.jpg")           # OpenCV default: BGR

# BGR -> RGB (for matplotlib, PIL, etc.)
rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)

# BGR -> grayscale (luminance-weighted)
gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)

# RGB -> BGR (reverse)
bgr2 = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)

# grayscale -> BGR (replicates channel, color image with no color)
bgr_from_gray = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)

BGR から HSV へ

uint8 に収まるよう、H に 0〜179 を(0〜360 でなく)使うのが、OpenCV の HSV です — 他のライブラリからコードを移植するときの、off-by-2x のバグの頻出源です。0〜255 なのが、S と V です。色ベースのセグメンテーションの頼みの綱が HSV です。hue が、明るさの変化におおよそ不変であるため — 色によるオブジェクトの追跡に使いましょう。

opencv
import cv2
import numpy as np

bgr = cv2.imread("photo.jpg")
hsv = cv2.cvtColor(bgr, cv2.COLOR_BGR2HSV)

# split channels
h, s, v = cv2.split(hsv)

# HSV ranges in OpenCV: H: 0-179, S: 0-255, V: 0-255
# (H is halved so it fits in 8-bit — full hue circle is 0-360)
print(h.max(), s.max(), v.max())   # 179 255 255

# back to BGR
bgr2 = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)

BGR から LAB へ

人間の知覚に近いのが、CIELAB です — 等しい数値の変化が大体等しく違って見えるため、色差の指標(ΔE)に使われます。明るさだけを符号化するのが、L チャンネルであるため、色を動かさず画像を明るくする最もきれいな方法が、L の編集です。標準の L の 0〜100 でなく、すべてのチャンネルに 0〜255 を使うのが、OpenCV の LAB です。

opencv
import cv2

bgr = cv2.imread("photo.jpg")

# BGR -> LAB (perceptually uniform color space)
lab = cv2.cvtColor(bgr, cv2.COLOR_BGR2LAB)
L, A, B = cv2.split(lab)

# L: lightness (0-255), A: green<->red, B: blue<->yellow
# useful for separating luminance from color

# LAB is great for color-difference metrics (delta-E)
# and for editing lightness without affecting color
import numpy as np
lab_bright = lab.copy()
lab_bright[:, :, 0] = np.clip(lab_bright[:, :, 0].astype(int) + 30, 0, 255)
bgr_bright = cv2.cvtColor(lab_bright, cv2.COLOR_LAB2BGR)

色の追跡(HSV)

最も単純なオブジェクトトラッカーが、HSV ベースの色の追跡です — hue の範囲を選び、しきい値処理し、最も大きい blob を見つけます。悪い照明(低飽和)の下で、似た色の背景オブジェクトで、反射面で失敗します。頑健な追跡のためには、(hue のヒストグラムのバックプロジェクションを使う)camshift/meanshift と組み合わせるか、動きを平滑化する Kalman フィルタを使いましょう。

opencv
import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()
    if not ret:
        break

    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # track a blue object
    lower = np.array([100, 80, 80])
    upper = np.array([130, 255, 255])
    mask = cv2.inRange(hsv, lower, upper)

    # find the largest blob
    contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL,
                                   cv2.CHAIN_APPROX_SIMPLE)
    if contours:
        c = max(contours, key=cv2.contourArea)
        if cv2.contourArea(c) > 500:
            (x, y), r = cv2.minEnclosingCircle(c)
            cv2.circle(frame, (int(x), int(y)), int(r), (0, 255, 255), 2)

    cv2.imshow("frame", frame)
    cv2.imshow("mask", mask)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()

チャンネルの Split と Merge

便利だが NumPy のインデックスより遅いのが、split/merge です。青チャンネルが img[:, :, 0] であり、split より修正が速いです。あなたのターゲットの色空間のために、正しい順で merge へチャンネルを必ず渡しましょう。「2 チャンネルをゼロにする」トリックが、単一の色チャンネルの貢献を可視化するクラシックな方法です。

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg")

# split into B, G, R channels (each is a 2-D array)
b, g, r = cv2.split(img)

# merge channels back (order matters!)
merged = cv2.merge([b, g, r])

# zero out one channel to visualize
zeros = np.zeros_like(b)
blue_only  = cv2.merge([b, zeros, zeros])
green_only = cv2.merge([zeros, g, zeros])
red_only   = cv2.merge([zeros, zeros, r])

# swap channels (e.g. fake RGB->BGR by swapping R and B)
swapped = cv2.merge([r, g, b])

その他の色空間

輝度(Y)とクロマ(Cr、Cb)を分離するのが、YCrCb です — JPEG と MPEG の圧縮の基礎であり、人間が明るさより色に敏感でないため、クロマの詳細を破棄します。白が、飽和にかかわらず L=1 にある点で HSV と異なるのが、HLS です。そのため、一部の陰影の効果には HLS が良いです。あなたが気にかけないものに対し操作を不変にする空間を選びましょう。

opencv
import cv2

bgr = cv2.imread("photo.jpg")

# YCrCb (used in JPEG compression)
ycrcb = cv2.cvtColor(bgr, cv2.COLOR_BGR2YCrCb)

# HLS (Hue, Lightness, Saturation — alternative to HSV)
hls = cv2.cvtColor(bgr, cv2.COLOR_BGR2HLS)

# YUV (used in video encoding)
yuv = cv2.cvtColor(bgr, cv2.COLOR_BGR2YUV)

# grayscale -> all spaces start from BGR, so chain conversions
gray_from_ycrcb = cv2.cvtColor(ycrcb, cv2.COLOR_YCrCb2BGR)
gray = cv2.cvtColor(gray_from_ycrcb, cv2.COLOR_BGR2GRAY)
12

ヒストグラム

ヒストグラムの計算

画像のリスト、チャンネルのリスト、省略可能なマスク(None = 画像全体)、ビン数、値の範囲を受け付けるのが、calcHist です。多次元のヒストグラム(2 次元の hue-飽和など)のためには、2 つのチャンネルと 2 つのビンサイズを渡しましょう — 色の追跡のためのヒストグラムのバックプロジェクションで使われます。独立に計算されるのが、各チャンネルのヒストグラムです。

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg", cv2.IMREAD_GRAYSCALE)

# calcHist(images, channels, mask, histSize, ranges)
hist = cv2.calcHist([img], [0], None, [256], [0, 256])
print(hist.shape)   # (256, 1)

# normalize to 0-1
hist /= hist.sum()

# multi-channel histogram (color)
bgr = cv2.imread("photo.jpg")
colors = ('b', 'g', 'r')
for i, col in enumerate(colors):
    h = cv2.calcHist([bgr], [i], None, [256], [0, 256])

ヒストグラムのプロット

ヒストグラムを可視化する最も簡単な方法が、Matplotlib です — しかし、凡例の色のために BGR を RGB へ変換するのを覚えましょう。さもないと、プロットの色がチャンネルのラベルと一致しません。左へ歪んだヒストグラムが暗い画像で、右が明るい画像であり、狭いスパイクが低コントラストを意味します。露出とホワイトバランスの問題の診断に、これを使いましょう。

opencv
import cv2
import numpy as np
import matplotlib.pyplot as plt

img = cv2.imread("photo.jpg")
colors = ('b', 'g', 'r')
for i, col in enumerate(colors):
    hist = cv2.calcHist([img], [i], None, [256], [0, 256])
    plt.plot(hist, color=col)
    plt.xlim([0, 256])

plt.title("Color Histogram")
plt.xlabel("Pixel value")
plt.ylabel("Frequency")
plt.show()

ヒストグラムの平坦化

フルの 0〜255 の範囲を使うようピクセルの強度を引き伸ばすのが、ヒストグラムの平坦化です — 低コントラストの画像には素晴らしいですが、ハイライトを吹き飛ばしノイズを増幅し得ます。BGR の 3 チャンネルすべてを直接平坦化してはいけません — 色が動きます。必ず輝度/色差の空間(YCrCb、LAB、HSV)へ変換し、輝度を平坦化し、戻しましょう。

opencv
import cv2

img = cv2.imread("dark.jpg", cv2.IMREAD_GRAYSCALE)

# global histogram equalization
eq = cv2.equalizeHist(img)

# equalization on color images: convert to YCrCb, equalize Y only
bgr = cv2.imread("color.jpg")
ycrcb = cv2.cvtColor(bgr, cv2.COLOR_BGR2YCrCb)
ycrcb[:, :, 0] = cv2.equalizeHist(ycrcb[:, :, 0])
eq_color = cv2.cvtColor(ycrcb, cv2.COLOR_YCrCb2BGR)

CLAHE(adaptive 平坦化)

グローバルな平坦化の本番品質の代替が、CLAHE です — 小さなタイル上で動くため、不均一な照明の画像で機能し、ノイズを吹き飛ばすのを避けるため、コントラストの増幅に上限を設けるのが、clipLimit です。デフォルトが、8x8 の tileGridSize で、小さいタイルが、より多くの局所適応を与えます。医療画像と文書の拡張の頼みの綱です。

opencv
import cv2

img = cv2.imread("dark.jpg", cv2.IMREAD_GRAYSCALE)

# CLAHE: Contrast Limited Adaptive Histogram Equalization
# equalizes small tiles, limiting amplification of noise
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
enhanced = clahe.apply(img)

# on color: equalize the L channel of LAB
bgr = cv2.imread("color.jpg")
lab = cv2.cvtColor(bgr, cv2.COLOR_BGR2LAB)
clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8, 8))
lab[:, :, 0] = clahe.apply(lab[:, :, 0])
enhanced_color = cv2.cvtColor(lab, cv2.COLOR_LAB2BGR)

ヒストグラムのバックプロジェクション

「どのピクセルが、私の ROI の色の分布に似ているか?」に答えるのが、ヒストグラムのバックプロジェクションです。サンプルから 2 次元の hue-飽和のヒストグラムを構築し、ターゲット画像上へバックプロジェクトすれば、確率マップが得られます。meanShift/camShift の追跡の基礎です — ターゲットの本物の色の分布を学習するため、固定の HSV 範囲よりはるかに頑健です。

opencv
import cv2
import numpy as np

img = cv2.imread("scene.jpg")
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

# take a small ROI of the target color (the object to track)
roi = hsv[100:150, 100:150]
roi_hist = cv2.calcHist([roi], [0, 1], None, [180, 256], [0, 180, 0, 256])
cv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX)

# backproject: each pixel = probability of belonging to the ROI's color
backproj = cv2.calcBackProject([hsv], [0, 1], roi_hist, [0, 180, 0, 256], 1)

# denoise and threshold
disc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
backproj = cv2.filter2D(backproj, -1, disc)
_, mask = cv2.threshold(backproj, 50, 255, cv2.THRESH_BINARY)

result = cv2.bitwise_and(img, img, mask=mask)
13

特徴検出

Harris の角検出器

小さい窓を任意の方向へ動かすことが大きな強度の変化を引き起こすか確認することで、角を検出するのが、Harris です — すべての方向で変わるのが角、1 方向で変わるのが縁、どの方向も変わらないのがフラットな領域です。corner-response のマップが出力であり、最大に対ししきい値処理しましょう(例:0.01 * max)。structure-tensor の計算のための近傍が、blockSize です。

opencv
import cv2
import numpy as np

img = cv2.imread("chessboard.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# cornerHarris(gray, blockSize, ksize, k)
# blockSize: neighborhood for corner detection
# ksize:     Sobel aperture (3, 5, 7)
# k:         Harris free parameter (0.04 - 0.06)
dst = cv2.cornerHarris(gray, 2, 3, 0.04)

# dilate to mark corners
dst = cv2.dilate(dst, None)

# threshold and mark in red
img[dst > 0.01 * dst.max()] = [0, 0, 255]

Shi-Tomasi(goodFeaturesToTrack)

スコアとして min(固有値1, 固有値2) を使い Harris を改善するのが、Shi-Tomasi です。これが、追跡のためのより安定した角を与えます。数に上限を設けるのが、maxCorners で、最も強い角の応答の分数が、qualityLevel です(0.01 = 最良の 1%)、検出された角の間の空間分離を強制するのが、minDistance です。Lucas-Kanade のオプティカルフロートラッカーのデフォルトの入力が、これです。

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# goodFeaturesToTrack returns the N strongest corners
corners = cv2.goodFeaturesToTrack(gray, maxCorners=100,
                                  qualityLevel=0.01,
                                  minDistance=10)
corners = np.int0(corners)

for c in corners:
    x, y = c.ravel()
    cv2.circle(img, (x, y), 3, (0, 0, 255), -1)

SIFT(スケール不変の特徴)

スケールと回転不変のキーポイントと、それぞれのための 128 次元の記述子を見つけるのが、SIFT です — 照明、視点、部分的な遮蔽に頑健です。何年も特許でしたが、OpenCV 4.4 で無料になりました。速度が二番目の、高精度のマッチングには SIFT を使いましょう。各キーポイントのスケールと向きを描くのが、DRAW_RICH_KEYPOINTS です。

opencv
import cv2

img = cv2.imread("photo.jpg", cv2.IMREAD_GRAYSCALE)

# SIFT was patented; free since OpenCV 4.4 (contrib not required)
sift = cv2.SIFT_create()

# detect keypoints
kp = sift.detect(img, None)

# detect and compute descriptors
kp, des = sift.detectAndCompute(img, None)
print(len(kp), des.shape)   # N, (N, 128)

# draw keypoints
out = cv2.drawKeypoints(img, kp, None,
                        flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

ORB(FAST + BRIEF)

FAST のキーポイント検出器と BRIEF の記述子を組み合わせるのが、ORB です — どちらも特許フリーであり、SIFT より約 10 倍速いです。そのため、モバイル/組み込みでのリアルタイムのマッチングの標準的な選択が、ORB です。記述子がバイナリであるため(SIFT の 128 float 対 32 バイト)、マッチングがハミング距離を使います。スケール/回転ではわずかに SIFT より頑健でありませんが、コストに見合った素晴らしさです。

opencv
import cv2

img = cv2.imread("photo.jpg", cv2.IMREAD_GRAYSCALE)

# ORB: free, fast alternative to SIFT
orb = cv2.ORB_create(nfeatures=1000)

kp, des = orb.detectAndCompute(img, None)
print(len(kp), des.shape)   # N, (N, 32) — binary descriptors

# draw keypoints
out = cv2.drawKeypoints(img, kp, None, color=(0, 255, 0),
                        flags=0)

# FAST alone (detector only, no descriptor)
fast = cv2.FastFeatureDetector_create(threshold=20)
kp = fast.detect(img, None)

FAST 検出器

候補の周りの 16 ピクセルの円が、中心よりすべて明るいかすべて暗い、N 個の連続したピクセルを持つかテストするのが、FAST です — 短絡するため、極めて速いです。キーポイントだけを返し、記述子はありません(記述子には BRIEF か ORB を使いましょう)。より低いしきい値 = より多くの(そしてノイズの多い)角。局所最大値で重複を取り除くのが、非最大抑制です。

opencv
import cv2

img = cv2.imread("photo.jpg", cv2.IMREAD_GRAYSCALE)

# FAST: speed-optimized corner detector (detector only)
fast = cv2.FastFeatureDetector_create(threshold=20,
                                      nonmaxSuppression=True)

kp = fast.detect(img, None)
print(f"{len(kp)} keypoints")

# tune the threshold
fast.setThreshold(30)
print(f"threshold is now {fast.getThreshold()}")

# turn off non-max suppression to get more (clustered) corners
fast.setNonmaxSuppression(False)
kp_all = fast.detect(img, None)

MSER(最大安定極値領域)

強度のしきい値の範囲をまたいで安定に留まる領域を見つけるのが、MSER です — テキスト検出(文字が blob 風である所)、ナンバープレート、シーンのテキストに理想的です。各領域が自分のしきい値で検出されるため、不均一な照明をよく扱えます。明らかに非テキストの除去のため、アスペクト比とサイズで結果をフィルタしましょう。

opencv
import cv2

img = cv2.imread("text.jpg", cv2.IMREAD_GRAYSCALE)

# MSER: detects stable connected regions across thresholds
mser = cv2.MSER_create()
regions, _ = mser.detectRegions(img)

# regions is a list of point arrays
out = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
for pts in regions:
    x, y, w, h = cv2.boundingRect(pts)
    if 5 < h < 50:    # filter by likely text size
        cv2.rectangle(out, (x, y), (x+w, y+h), (0, 255, 0), 1)
14

特徴マッチング

総当たりのマッチング

すべての記述子のペアを試みるのが、総当たりのマッチングです — 正確だが O(N*M) です。ORB のバイナリの記述子には NORM_HAMMING を、SIFT/SURF の float の記述子には NORM_L2 を使うしましょう。相互の最良のマッチだけを保つのが、crossCheck=True で(A の最良が B であり、その逆も)、多くの偽陽性を取り除きます。.distance を各マッチが持ち — 小さいほど良いです。

opencv
import cv2

img1 = cv2.imread("box.png", cv2.IMREAD_GRAYSCALE)
img2 = cv2.imread("scene.png", cv2.IMREAD_GRAYSCALE)

orb = cv2.ORB_create()
kp1, des1 = orb.detectAndCompute(img1, None)
kp2, des2 = orb.detectAndCompute(img2, None)

# for ORB (binary descriptors) use Hamming distance
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
matches = bf.match(des1, des2)

# sort by distance (best first)
matches = sorted(matches, key=lambda m: m.distance)

# draw top 20
out = cv2.drawMatches(img1, kp1, img2, kp2, matches[:20], None,
                      flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)

FLANN マッチング

(SIFT/SURF 用の)KD-tree か(ORB 用の)LSH を構築し近似マッチを見つけるのが、FLANN(Fast Library for Approximate Nearest Neighbors)です — たまのミスを代償に、大きな記述子のセットで総当たりよりはるかに速いです。精度と速度をトレードするのが、trees と checks のパラメータです。数千の特徴があるとき FLANN を使い、小さいセットには総当たりで十分です。

opencv
import cv2
import numpy as np

img1 = cv2.imread("box.png", cv2.IMREAD_GRAYSCALE)
img2 = cv2.imread("scene.png", cv2.IMREAD_GRAYSCALE)

sift = cv2.SIFT_create()
kp1, des1 = sift.detectAndCompute(img1, None)
kp2, des2 = sift.detectAndCompute(img2, None)

# FLANN parameters for SIFT (float descriptors)
FLANN_INDEX_KDTREE = 1
index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
search_params = dict(checks=50)
flann = cv2.FlannBasedMatcher(index_params, search_params)

matches = flann.knnMatch(des1, des2, k=2)

KNN マッチングとレシオテスト

特徴マッチングのための標準のフィルタが、Lowe のレシオテストです:最良のマッチが 2 番目の最良より有意に近い場合だけマッチを保ちます(典型的なしきい値 0.7〜0.8)。直観:両方の候補が同じくらい近いなら、マッチが曖昧で、おそらく誤りです。この単一のテストが、偽陽性の圧倒的多数を取り除きます。

opencv
import cv2

img1 = cv2.imread("box.png", cv2.IMREAD_GRAYSCALE)
img2 = cv2.imread("scene.png", cv2.IMREAD_GRAYSCALE)

sift = cv2.SIFT_create()
kp1, des1 = sift.detectAndCompute(img1, None)
kp2, des2 = sift.detectAndCompute(img2, None)

bf = cv2.BFMatcher(cv2.NORM_L2)
matches = bf.knnMatch(des1, des2, k=2)   # 2 nearest neighbors

# Lowe's ratio test: keep only unambiguous matches
good = []
for m, n in matches:
    if m.distance < 0.75 * n.distance:
        good.append(m)

out = cv2.drawMatches(img1, kp1, img2, kp2, good, None,
                      flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)

Homography(RANSAC)

はずれ値を無視しつつ、src を dst へマッピングする perspective 変換を計算するのが、RANSAC 付きの findHomography です。どのマッチがモデルと同意するか伝えるのが、インライアのマスクです。ピクセルであるのが、(5.0 の)再投影のしきい値で、低い = より厳密です。少なくとも 4 つの良いマッチが必要です。シーンの中の既知のオブジェクトの位置特定や、重なる写真の整列に、これを使いましょう。

opencv
import cv2
import numpy as np

img1 = cv2.imread("box.png", cv2.IMREAD_GRAYSCALE)
img2 = cv2.imread("scene.png", cv2.IMREAD_GRAYSCALE)

sift = cv2.SIFT_create()
kp1, des1 = sift.detectAndCompute(img1, None)
kp2, des2 = sift.detectAndCompute(img2, None)

bf = cv2.BFMatcher(cv2.NORM_L2)
matches = bf.knnMatch(des1, des2, k=2)
good = [m for m, n in matches if m.distance < 0.75 * n.distance]

# build point correspondences
src = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)
dst = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)

# RANSAC homography
H, mask = cv2.findHomography(src, dst, cv2.RANSAC, 5.0)
inliers = mask.ravel().tolist()
print(f"{sum(inliers)} inliers / {len(good)} matches")

オブジェクトの位置特定

これがクラシックなオブジェクト位置特定のパイプラインです:両方の画像で特徴を検出し、マッチし、RANSAC で homography をフィットさせ、その後、オブジェクトのバウンディングボックスをシーンへ投影します。平面のオブジェクトや、遠くの 3D オブジェクト(perspective が支配的な所)で機能します。テクスチャレス、対称、または高度に遮蔽されたオブジェクトでは失敗します — それらには、深層学習の検出器を使いましょう。

opencv
import cv2
import numpy as np

img1 = cv2.imread("box.png", cv2.IMREAD_GRAYSCALE)
img2 = cv2.imread("scene.png", cv2.IMREAD_GRAYSCALE)

sift = cv2.SIFT_create()
kp1, des1 = sift.detectAndCompute(img1, None)
kp2, des2 = sift.detectAndCompute(img2, None)

bf = cv2.BFMatcher(cv2.NORM_L2)
good = [m for m, n in bf.knnMatch(des1, des2, k=2)
        if m.distance < 0.75 * n.distance]

src = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)
dst = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)

H, _ = cv2.findHomography(src, dst, cv2.RANSAC, 5.0)

# project the object's corners into the scene
h, w = img1.shape
corners = np.float32([[0, 0], [w-1, 0], [w-1, h-1], [0, h-1]]).reshape(-1, 1, 2)
scene_corners = cv2.perspectiveTransform(corners, H)

out = cv2.cvtColor(img2, cv2.COLOR_GRAY2BGR)
cv2.polylines(out, [np.int32(scene_corners)], True, (0, 255, 0), 3)
15

顔の検出

Haar カスケード分類器

クラシックな Viola-Jones の検出器が、Haar カスケードです — CPU で速く、正面の顔に良いですが、モダンな深層学習の検出器(MTCNN、SSD、RetinaFace)より精度が低いです。マルチスケール検索を制御するのが、scaleFactor(>1)です — 1.1 = 10% のスケールステップ。小さい = より遅いがより徹底的です。重なる検出をフィルタするのが、minNeighbors で、偽陽性を減らすため引き上げましょう。

opencv
import cv2

# load a pretrained cascade (shipped with OpenCV)
cascade_path = cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
face_cascade = cv2.CascadeClassifier(cascade_path)

print(face_cascade.empty())   # False = loaded ok

img = cv2.imread("people.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# detectMultiScale(gray, scaleFactor, minNeighbors, minSize, maxSize)
faces = face_cascade.detectMultiScale(
    gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))

for (x, y, w, h) in faces:
    cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)

画像の中の顔検出

顔の ROI の内側での目(や笑顔)の検出が、標準の効率のトリックです:画像全体で目を探すと多くの偽陽性が得られますが、確認された顔の ROI の内側ではまれです。同梱の XML のディレクトリを指すのが、cv2.data.haarcascades です — 他のカスケード(目、笑顔、全身、プレート)も利用可能です。カスケードを呼ぶ「前に」ROI を切り出しましょう。

opencv
import cv2

face_cascade = cv2.CascadeClassifier(
    cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
eye_cascade = cv2.CascadeClassifier(
    cv2.data.haarcascades + "haarcascade_eye.xml")

img = cv2.imread("people.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (fx, fy, fw, fh) in faces:
    cv2.rectangle(img, (fx, fy), (fx+fw, fy+fh), (255, 0, 0), 2)

    # search for eyes INSIDE the face region (faster, fewer false positives)
    roi_gray = gray[fy:fy+fh, fx:fx+fw]
    roi_color = img[fy:fy+fh, fx:fx+fw]
    eyes = eye_cascade.detectMultiScale(roi_gray)
    for (ex, ey, ew, eh) in eyes:
        cv2.rectangle(roi_color, (ex, ey), (ex+ew, ey+eh), (0, 255, 0), 2)

動画の中の顔検出

Haar カスケードの速度のおかげで、CPU 上での Web カメラのリアルタイム顔検出が実現可能です。単純なプライバシー/匿名化の技法が、(顔領域のみの)ROI-ブラーのトリックです。フレームをまたぐ顔の追跡(ちらつきの回避)には、IoU により検出を関連付け、Kalman フィルタで平滑化しましょう — カスケード単独には、時間的な連続性がありません。

opencv
import cv2

face_cascade = cv2.CascadeClassifier(
    cv2.data.haarcascades + "haarcascade_frontalface_default.xml")

cap = cv2.VideoCapture(0)
while True:
    ret, frame = cap.read()
    if not ret:
        break

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.1, 5)

    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
        # blur the face for privacy
        frame[y:y+h, x:x+w] = cv2.GaussianBlur(
            frame[y:y+h, x:x+w], (25, 25), 30)

    cv2.imshow("face", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

横顔 / 側面の顔

ポーズ固有であるのが、Haar カスケードです — 正面のカスケードが側面の顔を見逃すため、プロファイルのカスケードと組み合わせましょう。片側で学習されているため、画像を水平に反転し、結果の座標を映し戻すことで、反対側が検出されます。それでも 3/4 のビューは見逃します — 1 つのモデルですべてのポーズを扱うのが、モダンな検出器(DNN、MTCNN)です。

opencv
import cv2

profile_cascade = cv2.CascadeClassifier(
    cv2.data.haarcascades + "haarcascade_profileface.xml")

img = cv2.imread("people.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# detect left-facing profiles
profiles = profile_cascade.detectMultiScale(gray, 1.1, 5)
for (x, y, w, h) in profiles:
    cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2)

# also detect right-facing by flipping the image
flipped = cv2.flip(gray, 1)
profiles_r = profile_cascade.detectMultiScale(flipped, 1.1, 5)
h, w = gray.shape
for (x, y, fw, fh) in profiles_r:
    cv2.rectangle(img, (w - x - fw, y), (w - x, y + fh), (255, 0, 0), 2)

DNN の顔検出

事前学習済みの Caffe/TensorFlow/ONNX モデルを実行できるのが、OpenCV の dnn モジュールです — Haar カスケードよりはるかに正確で、1 つのモデルですべてのポーズを扱うのが、SSD と ResNet ベースの顔検出器です。1 回で平均の引き算とスケーリングを行うのが、blobFromImage です。[0,1] に正規化された検出です。ピクセルボックスを得るには、(w, h, w, h) を掛けましょう。モデル:SSD(Caffe)、YuNet(ONNX、cv.FaceDetectorYN 経由)。

opencv
import cv2
import numpy as np

model = cv2.dnn.readNetFromCaffe(
    "deploy.prototxt", "weights.caffemodel")

img = cv2.imread("people.jpg")
h, w = img.shape[:2]

# build a 300x300 blob (mean subtraction + scale)
blob = cv2.dnn.blobFromImage(img, 1.0, (300, 300), (104, 177, 123))

model.setInput(blob)
detections = model.forward()   # shape (1, 1, N, 7)

for i in range(detections.shape[2]):
    conf = detections[0, 0, i, 2]
    if conf > 0.5:
        box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
        x1, y1, x2, y2 = box.astype(int)
        cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
        cv2.putText(img, f"{conf:.2f}", (x1, y1 - 5),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)
16

オブジェクト検出

HOG 記述子

縁の方向のヒストグラム経由で局所的な形状を記述するのが、HOG(Histogram of Oriented Gradients)です。線形 SVM と組み合わせると、クラシックなオブジェクト検出器です。直立したポーズの全身の歩行者に対し、事前学習済みの人検出器が機能します。速度と recall をトレードするのが、winStride と scale です。はるかに正確なのが、モダンな深層の検出器(YOLO、SSD)ですが、モデルファイルなしで CPU で動くのが、HOG です。

opencv
import cv2

img = cv2.imread("person.jpg", cv2.IMREAD_GRAYSCALE)

# create HOG descriptor with the default detector
hog = cv2.HOGDescriptor()
hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())

# detectMultiScale returns (rectangles, weights)
boxes, weights = hog.detectMultiScale(
    img, winStride=(8, 8), padding=(4, 4), scale=1.05)

for (x, y, w, h) in boxes:
    cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)

HOG 特徴の可視化

64x128 ピクセルであるのが、標準の HOG の窓です(INRIA の歩行者のサイズ)。パラメータ:窓(64x128)、ブロック(16x16)、ブロックの stride(8x8)、セル(8x8)、ビン(9)です。各記述子が 3780 次元です。カスタムオブジェクトを分類するには、多くの陽性/陰性サンプルの HOG 特徴を取り出し線形 SVM(scikit-learn)を学習し、setSVMDetector で検出器を設定しましょう。

opencv
import cv2

img = cv2.imread("person.jpg", cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img, (64, 128))   # standard HOG window

hog = cv2.HOGDescriptor((64, 128), (16, 16), (8, 8), (8, 8), 9)
descriptor = hog.compute(img)
print(descriptor.shape)   # (3780, 1)

# 9 bins per cell, 7x15 cells, 4 cells per block -> 3780 features
# this is the input vector to a linear SVM classifier

テンプレートマッチング

画像をまたいでテンプレートをスライドさせ、類似性のスコアを計算するのが、テンプレートマッチングです — 回転やスケールの変化のない、正確な(またはほぼ正確な)マッチでのみ機能します。最も頑健な方法が、TM_CCOEFF_NORMED で、結果が [-1, 1] に入ります。複数のマッチのためには、重なる検出を避けるため、レスポンスマップにしきい値処理し非最大抑制を適用しましょう。

opencv
import cv2
import numpy as np

img = cv2.imread("scene.png", cv2.IMREAD_GRAYSCALE)
template = cv2.imread("template.png", cv2.IMREAD_GRAYSCALE)
h, w = template.shape

# matchTemplate returns a correlation map
res = cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED)

# find the best match
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)

out = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
cv2.rectangle(out, top_left, bottom_right, (0, 255, 0), 2)

# find all matches above a threshold
loc = np.where(res >= 0.8)
for pt in zip(*loc[::-1]):
    cv2.rectangle(out, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 1)

マルチスケールのテンプレートマッチング

スケールの範囲を総当たりするのが、マルチスケールのテンプレートマッチングです — 遅いが、画像の中のテンプレートのサイズが未知のときに機能します。回転は依然扱えません。そのためには、角度の上も掃引する(非常に遅い)か、代わりに特徴マッチングを使う必要があります。本番のオブジェクト検出には、テンプレートマッチングでなく、学習済みの検出器(YOLO、SSD)を使いましょう。

opencv
import cv2
import numpy as np

img = cv2.imread("scene.png", cv2.IMREAD_GRAYSCALE)
template = cv2.imread("template.png", cv2.IMREAD_GRAYSCALE)

best = (-1, None, None)   # (score, location, scale)
for scale in np.linspace(0.5, 1.5, 20):
    resized = cv2.resize(template, None, fx=scale, fy=scale)
    rh, rw = resized.shape
    if rh > img.shape[0] or rw > img.shape[1]:
        continue
    res = cv2.matchTemplate(img, resized, cv2.TM_CCOEFF_NORMED)
    _, max_val, _, max_loc = cv2.minMaxLoc(res)
    if max_val > best[0]:
        best = (max_val, max_loc, scale)

score, (x, y), scale = best
h, w = template.shape
out = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
rw, rh = int(w * scale), int(h * scale)
cv2.rectangle(out, (x, y), (x + rw, y + rh), (0, 255, 0), 2)

DNN のオブジェクト検出(YOLO)

エクスポートされた YOLO/SSD/Faster-RCNN の重みを実行できるのが、OpenCV の dnn モジュールです — フルの DL フレームワークをインストールできないときに有用です。冗長なのが、YOLO の出力のパースです:center、size、objectness、クラスごとのスコアを持つ各検出です。重なるボックスを 1 つへ折りたたむため、NMSBoxes(非最大抑制)を必ず適用しましょう。リアルタイムには、YOLOv4-tiny を使うか、ONNX + より速いバックエンドへ切り替えましょう。

opencv
import cv2
import numpy as np

# load a YOLO model (weights + cfg)
net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")
with open("coco.names") as f:
    classes = [line.strip() for line in f.readlines()]

layer_names = net.getLayerNames()
out_layers = [layer_names[i - 1] for i in net.getUnconnectedOutLayers()]

img = cv2.imread("street.jpg")
blob = cv2.dnn.blobFromImage(img, 1/255.0, (416, 416), swapRB=True, crop=False)
net.setInput(blob)
outputs = net.forward(out_layers)

# parse YOLO output: each detection is [cx, cy, w, h, obj, class_scores...]
h, w = img.shape[:2]
boxes, confs, ids = [], [], []
for out in outputs:
    for det in out:
        scores = det[5:]
        cls = int(np.argmax(scores))
        conf = scores[cls]
        if conf > 0.5:
            cx, cy, bw, bh = (det[:4] * [w, h, w, h]).astype(int)
            boxes.append([cx - bw//2, cy - bh//2, bw, bh])
            confs.append(float(conf))
            ids.append(cls)

idxs = cv2.dnn.NMSBoxes(boxes, confs, 0.5, 0.4)   # non-max suppression
17

画像のセグメンテーション

K-Means クラスタリング

色によりピクセルをクラスタリングするのが、k-means です — 画像を K 個の支配的な色へポスタライズ/セグメント化する簡単な方法です。float32 のピクセルを(N, 3)として渡しましょう(空間クラスタリングのために xy 座標を加えるなら(N, 5))。より細かい色分離を与えるのが、K の増加です。空間的なまとまりのためには、各ピクセルを (x, y) 座標で拡張し、純粋な色の量子化のためには、BGR だけを使いましょう。

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg")
h, w = img.shape[:2]

# reshape to a list of pixels (N, 3) in float32
pixels = img.reshape(-1, 3).astype(np.float32)

# kmeans(data, K, criteria, attempts, flags)
K = 4
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 20, 1.0)
_, labels, centers = cv2.kmeans(pixels, K, None, criteria, 10,
                                cv2.KMEANS_RANDOM_CENTERS)

# rebuild the image with cluster centers
centers = np.uint8(centers)
seg = centers[labels.flatten()].reshape((h, w, 3))

GrabCut

対話的な前景抽出器が、GrabCut です — バウンディング矩形を与えれば、Gaussian Mixture Models で前景/背景を反復的にモデル化します。より細かい結果のためには、手動でピクセルをラベル付けした後(確定した前景 / 確定した背景)、GC_INIT_WITH_MASK で洗練させましょう。比較的単純な背景に対する単一の顕著なオブジェクトで良く機能します。

opencv
import cv2
import numpy as np

img = cv2.imread("person.jpg")
h, w = img.shape[:2]

# initialize mask (all probable background)
mask = np.zeros((h, w), np.uint8)

# define a rectangle around the foreground object
rect = (50, 50, w - 100, h - 100)

# internal scratch arrays
bgd = np.zeros((1, 65), np.float64)
fgd = np.zeros((1, 65), np.float64)

# run GrabCut: 5 iterations
cv2.grabCut(img, mask, rect, bgd, fgd, 5, cv2.GC_INIT_WITH_RECT)

# mask values: 0=bg, 1=fg, 2=probable bg, 3=probable fg
fg_mask = np.where((mask == 1) | (mask == 3), 255, 0).astype(np.uint8)
result = cv2.bitwise_and(img, img, mask=fg_mask)

Watershed

画像を地形図(強度 = 標高)として扱い、シードマーカーから盆地を「氾濫させる」のが、watershed です — 良いシードがなければ、深刻な過剰セグメンテーションを作ります。触れ合うオブジェクト(重なる硬貨など)のための、確定した前景のシードを生成するのが、距離変換のトリックです。マーカー:0 = 未知、1 = 背景、2..N = オブジェクト、-1 = 境界です。これが、クラシックな「触れ合うオブジェクトの分離」のパイプラインです。

opencv
import cv2
import numpy as np

img = cv2.imread("coins.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# threshold to separate coins from background
_, binary = cv2.threshold(gray, 0, 255,
                          cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)

# noise removal
kernel = np.ones((3, 3), np.uint8)
opening = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel, iterations=2)

# sure background area
sure_bg = cv2.dilate(opening, kernel, iterations=3)

# sure foreground: distance transform + threshold
dist = cv2.distanceTransform(opening, cv2.DIST_L2, 5)
_, sure_fg = cv2.threshold(dist, 0.5 * dist.max(), 255, 0)
sure_fg = np.uint8(sure_fg)

# unknown region (between sure fg and sure bg)
unknown = cv2.subtract(sure_bg, sure_fg)

# marker labelling
_, markers = cv2.connectedComponents(sure_fg)
markers = markers + 1
markers[unknown == 255] = 0

# watershed modifies markers in place
markers = cv2.watershed(img, markers)
img[markers == -1] = [255, 0, 0]   # boundaries in red

Flood Fill

魔法の杖のツールが、floodFill です — シードのピクセルから始まり、色がシード(FIXED_RANGE)か前のピクセルの loDiff/upDiff 以内である、接続されたすべてのピクセルを満たします。画像より 2 ピクセル大きくなければならないのが、マスクです(各側に 1 ピクセルの境界)。領域成長、簡単な背景置換、対話的な選択に有用です。

opencv
import cv2

img = cv2.imread("photo.jpg")
h, w = img.shape[:2]
mask = np.zeros((h + 2, w + 2), np.uint8)

# floodFill fills a connected region similar to the seed pixel
# (image, mask, seedPoint, newVal, loDiff, upDiff, flags)
cv2.floodFill(img, mask, (100, 100), (0, 255, 0),
              loDiff=(20, 20, 20), upDiff=(20, 20, 20),
              flags=8 | cv2.FLOODFILL_FIXED_RANGE)

# FLOODFILL_FIXED_RANGE: compare to the seed pixel (strict)
# 4-connectivity (4) or 8-connectivity (8)

# extract the filled mask
filled_mask = mask[1:-1, 1:-1]   # the mask is padded by 1

Connected Components

一意の整数で各白い領域をラベル付けするのが、connectedComponents です — カウント、面積、中心だけが必要なとき、findContours より速いです。バウンディングボックスと面積も返すのが、connectedComponentsWithStats です。常に背景であるのが、ラベル 0 です。デフォルトの接続性が 8(対角を含む)で、より厳密には connectivity=4 を渡しましょう。粒子のカウントと blob 分析に、これを使いましょう。

opencv
import cv2
import numpy as np

img = cv2.imread("blobs.png", cv2.IMREAD_GRAYSCALE)
_, binary = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

# connectedComponents returns (num_labels, labels)
num, labels = cv2.connectedComponents(binary)
print(f"found {num - 1} objects (label 0 is background)")

# connectedComponentsWithStats also gives area and bounding box
num, labels, stats, centroids = cv2.connectedComponentsWithStats(binary)
for i in range(1, num):
    x, y, w, h, area = stats[i]
    cx, cy = centroids[i]
    cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 1)
    cv2.putText(img, str(area), (x, y - 5),
                cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0, 0, 255), 1)

Mean-Shift / PyrMeanShiftFiltering

縁を保ちつつ、似た色の領域を「平坦化する」非パラメトリックなセグメンテーションが、pyrMeanShiftFiltering です — 輪郭ベースのセグメンテーションの前の前処理ステップとしてよく使われます。アルゴリズムが空間的にどれほど遠く見るかの制御が、sp(空間半径)で、色の許容の制御が、sr(色の半径)です。より大きい、より滑らかな領域を作るのが、大きい値です。

opencv
import cv2

img = cv2.imread("photo.jpg")

# pyrMeanShiftFiltering: edge-preserving smoothing that homogenizes regions
# (spatialRadius, colorRadius) — larger values merge more
filtered = cv2.pyrMeanShiftFiltering(img, sp=20, sr=40)

# now segment on the filtered image
gray = cv2.cvtColor(filtered, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 0, 255,
                          cv2.THRESH_BINARY + cv2.THRESH_OTSU)

contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL,
                               cv2.CHAIN_APPROX_SIMPLE)
out = img.copy()
cv2.drawContours(out, contours, -1, (0, 255, 0), 2)
18

カメラキャリブレーション

チェスボードのキャリブレーション

既知のパターン(チェスボードが標準 — 角が検出しやすいためです)の画像から、内部の行列(焦点距離、主点)とレンズの歪みの係数を見つけるのが、カメラキャリブレーションです。多様な角度から約 10〜20 枚の画像が必要です。サブピクセル精度へ角を洗練させるのが、cornerSubPix で — 良いキャリブレーションには不可欠です。findChessboardCorners へ渡すパターンのサイズが、内部の角です(正方形 - 1)。

opencv
import cv2
import numpy as np
import glob

# prepare object points (0,0,0), (1,0,0), ..., for a 7x6 board
objp = np.zeros((6 * 7, 3), np.float32)
objp[:, :2] = np.mgrid[0:7, 0:6].T.reshape(-1, 2)

objpoints = []   # 3-D real-world points
imgpoints = []   # 2-D image points

for fname in glob.glob("calib/*.jpg"):
    img = cv2.imread(fname)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # findChessboardCorners returns corners (or None)
    ret, corners = cv2.findChessboardCorners(gray, (7, 6), None)
    if ret:
        # refine to sub-pixel accuracy
        corners2 = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1),
            (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001))
        objpoints.append(objp)
        imgpoints.append(corners2)

# calibrate
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(
    objpoints, imgpoints, gray.shape[::-1], None, None)
print("camera matrix:\n", mtx)

画像の undistort

キャリブレーションのパラメータを使い、放射と接線のレンズの歪みを取り除くのが、undistort です。動画のためには、initUndistortRectifyMap でマップを一度事前計算し、各フレームに remap を適用しましょう — 繰り返しの undistort 呼び出しよりはるかに速いです。すべてのピクセルを(黒い境界と共に)保つのが、alpha=1 付きの getOptimalNewCameraMatrix で、有効な領域へ切り出すのが、alpha=0 です。

opencv
import cv2
import numpy as np

# mtx, dist come from calibrateCamera
img = cv2.imread("distorted.jpg")
h, w = img.shape[:2]

# method 1: simple undistort
undistorted = cv2.undistort(img, mtx, dist)

# method 2: pre-compute the maps for speed (run once, reuse many times)
newcameramtx, roi = cv2.getOptimalNewCameraMatrix(
    mtx, dist, (w, h), 1, (w, h))
mapx, mapy = cv2.initUndistortRectifyMap(
    mtx, dist, None, newcameramtx, (w, h), cv2.CV_16SC2)
undistorted2 = cv2.remap(img, mapx, mapy, cv2.INTER_LINEAR)

# crop to the valid ROI
x, y, rw, rh = roi
undistorted2 = undistorted2[y:y+rh, x:x+rw]

ポーズ推定(ArUco)

ポーズ推定のために使われる、正方形の基準マーカー(QR コードのような)が、ArUco マーカーです — マーカーの物理サイズとカメラのキャリブレーションが与えられれば、カメラに対する 3 次元の回転(rvec)と平行移動(tvec)が得られます。利用可能なのが、opencv-contrib です。マーカーのローカルな X/Y/Z の軸を描くのが、drawFrameAxes です — 赤 = X、緑 = Y、青 = Z、長さはメートルです。

opencv
import cv2

# load a predefined ArUco dictionary
aruco_dict = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_4X4_50)
params = cv2.aruco.DetectorParameters()
detector = cv2.aruco.ArucoDetector(aruco_dict, params)

img = cv2.imread("marker.png")
corners, ids, rejected = detector.detectMarkers(img)

if ids is not None:
    cv2.aruco.drawDetectedMarkers(img, corners, ids)

    # estimate pose (marker size in meters, camera matrix, distortion)
    rvecs, tvecs, _ = cv2.aruco.estimatePoseSingleMarkers(
        corners, 0.05, mtx, dist)
    for rvec, tvec in zip(rvecs, tvecs):
        cv2.drawFrameAxes(img, mtx, dist, rvec, tvec, 0.05)

基準ポーズ(SolvePnP)

N 個の 3D-2D の対応からカメラのポーズを回復するのが、solvePnP(Perspective-n-Point)です — 少なくとも 4 点が必要です。精度のためには SOLVEPNP_ITERATIVE(デフォルト)を、平面のターゲットには SOLVEPNP_IPPE を使いましょう。回転ベクトル(軸 × 角度)であるのが、rvec です。3x3 の行列への変換には、Rodrigues を。マーカーベースの AR と 6 自由度の追跡の基礎です。

opencv
import cv2
import numpy as np

# 3-D coordinates of known object points (e.g. a cube corner)
obj_points = np.array([
    [0, 0,  0], [1, 0,  0], [1, 1,  0], [0, 1,  0],
    [0, 0, -1], [1, 0, -1], [1, 1, -1], [0, 1, -1],
], dtype=np.float32)

# corresponding 2-D image points (detected via feature matching etc.)
img_points = np.array([
    [120, 90], [220, 88], [225, 190], [115, 195],
    [80, 60],  [240, 55], [248, 210], [70, 215],
], dtype=np.float32)

# solvePnP(objectPoints, imagePoints, cameraMatrix, distCoeffs)
ret, rvec, tvec = cv2.solvePnP(obj_points, img_points, mtx, dist)
print("rotation:", rvec.ravel())
print("translation:", tvec.ravel())

# project the 3-D points back to verify
proj, _ = cv2.projectPoints(obj_points, rvec, tvec, mtx, dist)

再投影誤差

キャリブレーション品質のゴールドスタンダードが、再投影誤差です — 投影された 3 次元点が、検出された 2 次元点からどれほど遠くに着地するかを測ります。0.5 px 未満の平均が、良いキャリブレーションであり、1 px を超える通常の意味は、悪い画像セット、間違ったパターンサイズ、動きのブラーです。悪いキャリブレーション画像を見つけて破棄するのを助けるのが、画像ごとの誤差です。

opencv
import cv2
import numpy as np

# after calibrateCamera or solvePnP, check accuracy
mean_err = 0
total = 0
for i in range(len(objpoints)):
    # project the 3-D points using the estimated pose
    proj, _ = cv2.projectPoints(objpoints[i], rvecs[i], tvecs[i], mtx, dist)
    err = cv2.norm(imgpoints[i], proj, cv2.NORM_L2) / len(proj)
    mean_err += err
    total += 1

print(f"mean reprojection error: {mean_err / total:.3f} px")
# good calibrations are typically < 0.5 px per corner
19

深度とステレオ

ステレオの視差マップ

レクティファイされたステレオペアの視差マップ(左右の間のピクセルのオフセット)を計算するのが、StereoBM です — 近いオブジェクトがより大きな視差を持ちます。16 の倍数でなければならないのが、numDisparities で、奇数でなければならないのが、blockSize です。16 でスケールされた int16 が出力です(ピクセル視差のため 16.0 で割りましょう)。より遅いがはるかに正確なのが、StereoSGBM(半グローバルのブロックマッチング)です。

opencv
import cv2

# stereo pair (rectified: corresponding points on the same row)
imgL = cv2.imread("left.png", cv2.IMREAD_GRAYSCALE)
imgR = cv2.imread("right.png", cv2.IMREAD_GRAYSCALE)

# StereoBM (block matching, fast)
stereo = cv2.StereoBM_create(numDisparities=16, blockSize=15)
disparity = stereo.compute(imgL, imgR)

# normalize for display
disp_vis = cv2.normalize(disparity, None, 0, 255,
                         cv2.NORM_MINMAX, cv2.CV_8U)

StereoSGBM

走査線をまたぐ平滑性を強制するのが、StereoSGBM です(半グローバルのマッチング)— 約 5 倍のランタイムを代償に、StereoBM よりはるかに正確です。それぞれ、1 と >1 の視差変化を罰するのが、P1/P2 で、経験則が P1=8*C*blockSize² と P2=32*C*blockSize² です(C はチャンネル数です)。小さいノイズの視差領域をフィルタするのが、speckle* のパラメータです。

opencv
import cv2

imgL = cv2.imread("left.png", cv2.IMREAD_GRAYSCALE)
imgR = cv2.imread("right.png", cv2.IMREAD_GRAYSCALE)

sgbm = cv2.StereoSGBM_create(
    minDisparity=0,
    numDisparities=128,
    blockSize=5,
    P1=8 * 3 * 5 * 5,
    P2=32 * 3 * 5 * 5,
    disp12MaxDiff=1,
    uniquenessRatio=10,
    speckleWindowSize=100,
    speckleRange=32,
)

disparity = sgbm.compute(imgL, imgR)
disp_vis = cv2.normalize(disparity, None, 0, 255,
                         cv2.NORM_MINMAX, cv2.CV_8U)

ステレオキャリブレーションとレクティフィケーション

画像がレクティファイされることを要求するのが、ステレオマッチングです — 対応する点が行を共有するよう、エピポーラ線が水平に整列します。パイプライン:各カメラをキャリブレーションし、その間の R と T を見つけるためステレオキャリブレーションし、レクティフィケーションの変換を計算するのが stereoRectify で、その後、各フレームに一度 remap します。レクティフィケーション後、視差の計算が、行に沿った 1 次元の検索になります。

opencv
import cv2
import numpy as np

# calibrate each camera separately, then stereo-calibrate
ret, mtxL, distL, rvecsL, tvecsL = cv2.calibrateCamera(
    objpoints, imgpointsL, grayL.shape[::-1], None, None)
ret, mtxR, distR, rvecsR, tvecsR = cv2.calibrateCamera(
    objpoints, imgpointsR, grayR.shape[::-1], None, None)

# stereo calibration: finds the rigid transform between cameras
flags = cv2.CALIB_FIX_INTRINSIC
ret, mtxL, distL, mtxR, distR, R, T, E, F = cv2.stereoCalibrate(
    objpoints, imgpointsL, imgpointsR, mtxL, distL, mtxR, distR,
    grayL.shape[::-1], flags=flags)

# stereo rectification: aligns epipolar lines to be horizontal
R1, R2, P1, P2, Q, _, _ = cv2.stereoRectify(
    mtxL, distL, mtxR, distR, grayL.shape[::-1], R, T)

# pre-compute the rectification maps
mapL1, mapL2 = cv2.initUndistortRectifyMap(
    mtxL, distL, R1, P1, grayL.shape[::-1], cv2.CV_16SC2)
mapR1, mapR2 = cv2.initUndistortRectifyMap(
    mtxR, distR, R2, P2, grayR.shape[::-1], cv2.CV_16SC2)

rectL = cv2.remap(imgL, mapL1, mapL2, cv2.INTER_LINEAR)
rectR = cv2.remap(imgR, mapR1, mapR2, cv2.INTER_LINEAR)

視差からの深度

視差に反比例するのが、深度です:depth = focal × baseline / disparity です。一貫した単位でなければならないのが、ベースライン(カメラの分離)と焦点距離です(焦点には通常ピクセル、ベースラインにはメートルが、メートルの深度を与えます)。遠くのオブジェクトに対しノイズの多いのが、視差です(小さい視差、大きな深度誤差)— そのため、遠距離のためにステレオカメラが広いベースラインを必要とします。

opencv
import cv2
import numpy as np

# given a disparity map and the stereo baseline + focal length:
# depth = (focal_length * baseline) / disparity

focal = 700.0       # pixels (from camera matrix)
baseline = 0.1      # meters (distance between cameras)

disparity = sgbm.compute(rectL, rectR).astype(np.float32) / 16.0

# avoid division by zero
disparity[disparity <= 0] = 0.1
depth = (focal * baseline) / disparity   # in meters

# cap to a sensible range
depth = np.clip(depth, 0.1, 100.0)
depth_vis = cv2.normalize(depth, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U)

オプティカルフロー(Lucas-Kanade)

疎のオプティカルフローを計算するのが、Lucas-Kanade です — 小さい局所的な動きを仮定し、フレームをまたいでキーポイントのセットを追跡します。中程度の動きには速く正確で、大きいか速い動きでは失敗します(ピラミッドを使いましょう、calcOpticalFlowPyrLK が既に行っています)。ポイントが正常に追跡されたことを意味するのが、status==1 です。ピクセルごとの密なフローには、calcOpticalFlowFarneback を — はるかに遅いが、完全なモーションフィールドを作ります。

opencv
import cv2
import numpy as np

cap = cv2.VideoCapture("traffic.mp4")
ret, prev = cap.read()
prev_gray = cv2.cvtColor(prev, cv2.COLOR_BGR2GRAY)

# detect good features to track
prev_pts = cv2.goodFeaturesToTrack(prev_gray, 100, 0.3, 7)

while True:
    ret, frame = cap.read()
    if not ret:
        break
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # sparse optical flow (Lucas-Kanade)
    next_pts, status, err = cv2.calcOpticalFlowPyrLK(
        prev_gray, gray, prev_pts, None)

    good_new = next_pts[status == 1]
    good_old = prev_pts[status == 1]

    for new, old in zip(good_new, good_old):
        a, b = new.ravel()
        c, d = old.ravel()
        cv2.line(frame, (int(a), int(b)), (int(c), int(d)), (0, 255, 0), 2)
        cv2.circle(frame, (int(a), int(b)), 3, (0, 0, 255), -1)

    cv2.imshow("flow", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
    prev_gray = gray.copy()
    prev_pts = good_new.reshape(-1, 1, 2)

cap.release()
20

ユーティリティとヒント

パフォーマンスの測定

OpenCV の呼び出しをベンチマークする最もきれいな方法が、TickMeter です。実時間のミリ秒を返すのが、getTimeMilli です。サイクル正確なタイミングを与えるのが、getTickCount/getTickFrequency です。ジッターを償却するため、多くの反復にわたって必ず平均し、ベンチマーク時には cv2.imshow を無効化しましょう(GUI の描画が支配します)。基礎の並列バックエンド(TBB/OpenMP)を制御するのが、setNumThreads です。

opencv
import cv2
import numpy as np

img = cv2.imread("photo.jpg")

# TickMeter: high-precision timer
tm = cv2.TickMeter()
tm.start()
for _ in range(100):
    blurred = cv2.GaussianBlur(img, (5, 5), 0)
tm.stop()
print(f"avg: {tm.getTimeMilli() / 100:.3f} ms")

# getTickCount / getTickFrequency
t0 = cv2.getTickCount()
edges = cv2.Canny(img, 50, 150)
t1 = cv2.getTickCount()
print(f"Canny: {(t1 - t0) / cv2.getTickFrequency() * 1000:.2f} ms")

# set USE_AVX / thread count
cv2.setNumThreads(4)
print(cv2.getNumThreads())

マウスイベント

名前付きのウィンドウ上のマウスイベントのためのハンドラを登録するのが、setMouseCallback です — 対話的な ROI の選択、注釈ツール、簡単なペイントアプリに有用です。よくあるイベント:LBUTTONDOWN、LBUTTONUP、MOUSEMOVE、RBUTTONDOWN です。トップレベルの(かグローバルの)関数でなければならないのが、ハンドラで、コールバックのシグネチャが固定であるため、状態共有の標準的な方法が、グローバルです。

opencv
import cv2
import numpy as np

drawing = False
ix, iy = -1, -1

def on_mouse(event, x, y, flags, param):
    global drawing, ix, iy
    if event == cv2.EVENT_LBUTTONDOWN:
        drawing = True
        ix, iy = x, y
    elif event == cv2.EVENT_MOUSEMOVE and drawing:
        cv2.rectangle(img, (ix, iy), (x, y), (0, 255, 0), -1)
    elif event == cv2.EVENT_LBUTTONUP:
        drawing = False
        cv2.rectangle(img, (ix, iy), (x, y), (0, 255, 0), -1)

img = np.zeros((512, 512, 3), np.uint8)
cv2.namedWindow("canvas")
cv2.setMouseCallback("canvas", on_mouse)

while True:
    cv2.imshow("canvas", img)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cv2.destroyAllWindows()

Trackbar

スクリプトを再起動せず、対話的にパラメータを調整できるのが、トラックバーです — 良いしきい値、カーネルサイズ、HSV 範囲の発見には非常に有用です。変化のたびに呼ばれるのが、コールバックです(メインのループで getTrackbarPos をポーリングするなら no-op で構いません)。名前付きのウィンドウ上で作られ、getTrackbarPos(window, name) で読まれなければならないのが、トラックバーです。

opencv
import cv2
import numpy as np

def nothing(x):
    pass

img = np.zeros((300, 512, 3), np.uint8)
cv2.namedWindow("image")

# create trackbars
cv2.createTrackbar("R", "image", 0, 255, nothing)
cv2.createTrackbar("G", "image", 0, 255, nothing)
cv2.createTrackbar("B", "image", 0, 255, nothing)
cv2.createTrackbar("switch", "image", 0, 1, nothing)

while True:
    cv2.imshow("image", img)
    if cv2.waitKey(1) & 0xFF == 27:    # Esc to quit
        break

    r = cv2.getTrackbarPos("R", "image")
    g = cv2.getTrackbarPos("G", "image")
    b = cv2.getTrackbarPos("B", "image")
    s = cv2.getTrackbarPos("switch", "image")

    if s == 0:
        img[:] = 0
    else:
        img[:] = [b, g, r]

cv2.destroyAllWindows()

ROI セレクタ

ユーザーが長方形をドラッグし Enter/Space を押す、対話的なウィンドウを開くのが、selectROI です — 自分のマウスコールバックを書くよりはるかに楽です。キャンセルするには「c」を押します(すべてゼロを返します)。1 つずつ複数の長方形を選ばせるのが、selectROIs です。(x, y, w, h) であるのが、返されるタプルで、切り出すのが img[y:y+h, x:x+w] です。

opencv
import cv2

img = cv2.imread("photo.jpg")

# built-in ROI selector (drag a rectangle)
roi = cv2.selectROI("select", img, showCrosshair=True, fromCenter=False)
cv2.destroyAllWindows()

x, y, w, h = roi
cropped = img[y:y+h, x:x+w]

# multiple ROIs
rois = cv2.selectROIs("select", img, showCrosshair=True, fromCenter=False)
for r in rois:
    x, y, w, h = r
    cv2.imshow("roi", img[y:y+h, x:x+w])
    cv2.waitKey(0)
cv2.destroyAllWindows()

よくある落とし穴

OpenCV のバグの大多数を引き起こす 5 つの落とし穴:BGR/RGB の混乱(赤と青が入れ替わる)、uint8 のオーバーフロー(暗い/明るいアーティファクト)、座標の順序(off-by-one の ROI)、ファイル欠落の None(以後の操作が謎のエラーでクラッシュする)、waitKey の忘れ(ウィンドウが更新されない)です。早く内面化しましょう — すべての OpenCV の開発者が、それぞれ少なくとも 1 回ぶつかります。

opencv
import cv2
import numpy as np

# 1. BGR vs RGB — imshow expects BGR; matplotlib expects RGB
img = cv2.imread("p.jpg")
# plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))   # correct
# plt.imshow(img)                                     # colors look wrong

# 2. uint8 overflow — use cv2 ops or upcast
a = np.array([200], np.uint8)
print(a + 100)        # [44]   (wraps, WRONG)
print(cv2.add(a, 100))  # [[255]] (saturates, RIGHT)

# 3. (x, y) vs (row, col) — drawing uses (x,y), NumPy uses [y,x]
cv2.rectangle(img, (10, 20), (110, 120), (0, 255, 0), 2)  # x=10..110
roi = img[20:120, 10:110]   # rows 20..120, cols 10..110 (same region)

# 4. None returned by imread when the file is missing
img = cv2.imread("missing.jpg")
if img is None:
    raise FileNotFoundError("could not read image")

# 5. waitKey is mandatory for imshow to actually render
cv2.imshow("img", img)
cv2.waitKey(1)   # without this, the window may stay blank

Was this helpful?

Learning path

Learn from scratch

Learn this language from the ground up with structured lessons.