サムネイル
OpenCV（Open Source Computer Vision）は、コンピュータビジョンタスクをサポートするオープンソースのライブラリです。
import cv2
image = cv2.imread('image.jpg')
cv2.imshow('Image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
import cv2
image = cv2.imread('image.jpg')
resized_image = cv2.resize(image, (800, 600))
adjusted_image = cv2.convertScaleAbs(resized_image, alpha=1.2, beta=10)
blurred_image = cv2.GaussianBlur(adjusted_image, (5, 5), 0)
cv2.imshow('Image', blurred_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
import cv2
image = cv2.imread('image.jpg')
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
ret, binary_image = cv2.threshold(gray_image, 127, 255, cv2.THRESH_BINARY)
cv2.imshow('Image', binary_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
import cv2
video = cv2.VideoCapture('video.mp4')
while video.isOpened():
    ret, frame = video.read()
    if not ret:
        break
    # フレームの表示
    cv2.imshow('Frame', frame)
    # 'q'キーで終了
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
video.release()
cv2.destroyAllWindows()
import cv2
camera = cv2.VideoCapture(0)
while camera.isOpened():
    ret, frame = camera.read()
    if not ret:
        break
    # フレームの表示
    cv2.imshow('Frame', frame)
    # 'q'キーで終了
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
camera.release()
cv2.destroyAllWindows()
import cv2
video = cv2.VideoCapture('video.mp4')
while video.isOpened():
    ret, frame = video.read()
    if not ret:
        break
    # フレームの処理（例: フレームのリサイズ）
    resized_frame = cv2.resize(frame, (640, 480))
    # 処理後のフレームの表示
    cv2.imshow('Frame', resized_frame)
    # 'q'キーで終了
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
video.release()
cv2.destroyAllWindows()
import cv2
net = cv2.dnn.readNetFromCaffe('deploy.prototxt', 'model.caffemodel')
image = cv2.imread('image.jpg')
blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0))
net.setInput(blob)
detections = net.forward()
for i in range(detections.shape[2]):
    confidence = detections[0, 0, i, 2]
    if confidence > 0.5:
        box = detections[0, 0, i, 3:7] * np.array([image.shape[1], image.shape[0], image.shape[1], image.shape[0]])
        (startX, startY, endX, endY) = box.astype("int")
        cv2.rectangle(image, (startX, startY), (endX, endY), (0, 255, 0), 2)
cv2.imshow("Image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
import cv2
tracker = cv2.TrackerKCF_create()
import cv2
image = cv2.imread('image.jpg')
detector = cv2.SIFT_create()
keypoints = detector.detect(image, None)
image_with_keypoints = cv2.drawKeypoints(image, keypoints, None)
cv2.imshow('Image', image_with_keypoints)
cv2.waitKey(0)
cv2.destroyAllWindows()
import cv2
image = cv2.imread('image.jpg')
detector = cv2.SIFT_create()
descriptor = cv2.SIFT_create()
keypoints = detector.detect(image, None)
keypoints, descriptors = descriptor.compute(image, keypoints)
image_with_keypoints = cv2.drawKeypoints(image, keypoints, None)
cv2.imshow('Image', image_with_keypoints)
cv2.waitKey(0)
cv2.destroyAllWindows()
import cv2
import numpy as np
grid_size = (9, 6)
images = [cv2.imread(f'calibration_image{i}.jpg') for i in range(1, 10)]
object_points = []
image_points = []
for image in images:
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    ret, corners = cv2.findChessboardCorners(gray, grid_size, None)
    if ret:
        object_points.append(np.zeros((grid_size[0] * grid_size[1], 3), np.float32))
        object_points[-1][:, :2] = np.mgrid[0:grid_size[0], 0:grid_size[1]].T.reshape(-1, 2)
        image_points.append(corners)
ret, camera_matrix, dist_coeffs, rvecs, tvecs = cv2.calibrateCamera(object_points, image_points, gray.shape[::-1], None, None)
print("Camera Matrix:")
print(camera_matrix)
print("Distortion Coefficients:")
print(dist_coeffs)
import cv2
import numpy as np
previous_frame = None
video = cv2.VideoCapture('video.mp4')
while video.isOpened():
    ret, frame = video.read()
    if not ret:
        break
    # グレースケールへの変換
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # フレーム差分の計算
    if previous_frame is None:
        previous_frame = gray
        continue
    frame_diff = cv2.absdiff(previous_frame, gray)
    threshold = cv2.threshold(frame_diff, 30, 255, cv2.THRESH_BINARY)[1]
    # モーション領域の検出
    contours, _ = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    for contour in contours:
        if cv2.contourArea(contour) > 1000:
            (x, y, w, h) = cv2.boundingRect(contour)
            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
    # フレームの表示
    cv2.imshow('Frame', frame)
    # 'q'キーで終了
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
    # 現在のフレームを前のフレームとして保存
    previous_frame = gray
video.release()
cv2.destroyAllWindows()
import cv2
image = cv2.imread('image.jpg')
clone = image.copy()
rect = (100, 100, 200, 200)
mask = np.zeros(image.shape[:2], np.uint8)
mask[rect[1]:rect[1] + rect[3], rect[0]:rect[0] + rect[2]] = 255
inpainted = cv2.inpaint(clone, mask, 3, cv2.INPAINT_TELEA)
cv2.imshow('Image', inpainted)
cv2.waitKey(0)
cv2.destroyAllWindows()
OpenCVの検出機とメソッド例:
1. Haar Cascade 物体検出器:
   - `cv2.CascadeClassifier.detectMultiScale(image, scaleFactor, minNeighbors, flags, minSize, maxSize)`
2. HOG 特徴検出器:
   - `cv2.HOGDescriptor()`
   - `compute()`: HOG特徴を計算
   - `detectMultiScale()`: 物体検出
3. ディープラーニングをベースにした物体検出器:
   - `cv2.dnn.readNet(model, config)`
   - `net.forward(layerNames)`: フォワードパスの実行
   - `cv2.dnn.blobFromImage(image, scalefactor, size, mean, swapRB, crop)`
4. SIFT 特徴検出器:
   - `cv2.SIFT_create()`
   - `detectAndCompute(image, mask)`
5. ORB 特徴検出器:
   - `cv2.ORB_create()`
   - `detectAndCompute(image, mask)`
6. セマンティックセグメンテーションのモデル:
   - `cv2.dnn.readNet(model, config)`
   - `net.forward(layerNames)`
7. 姿勢推定のモデル:
   - `cv2.dnn.readNet(model, config)`
   - `net.forward(outputLayerNames)`
これらはOpenCVモジュールの一部の機能です。詳細な情報や他の機能については、公式のOpenCVドキュメントを参照してください。