画像ファイルのグラフ値をPythonで数値として読み取りたい
前回実施した結果は,こちらです.
PythonのOpenCVライブラリを使うという意味では同じなのですが,
前回とは少し異なるやり方で,グラフ値の読み取りを実行してみました.
<読み取るグラフはこちら>
残念ながら,これもうまくいかなかったのですが,参考として残しておこうと思います.
read_graph_cv2.py
# -*- coding: utf-8 -*-
import cv2
import numpy as np
from matplotlib import pyplot as plt
import japanize_matplotlib
image = "torque.jpg"
k = 1
th = 100
y_min = 50
y_max = 110
x_min = 600
x_max = 7800
def get_profile():
# 画像を読み込み、前処理を行う
img = cv2.imread(image, 0)
kernel = np.ones((k, k), np.uint8)
ret, img = cv2.threshold(img, th, 255, cv2.THRESH_BINARY)
img = cv2.dilate(img, kernel, iterations=1)
img = cv2.erode(img, kernel, iterations=1)
# 画像の高さと幅を取得
h, w = img.shape
# XYデータを格納するリスト
profile = []
# グリッド線と外枠を検出し、無視する
edges = cv2.Canny(img, 50, 150)
lines = cv2.HoughLinesP(edges, 1, np.pi / 180, threshold=100, minLineLength=100, maxLineGap=10)
mask = np.ones_like(img) * 255
if lines is not None:
for line in lines:
x1, y1, x2, y2 = line[0]
cv2.line(mask, (x1, y1), (x2, y2), 0, 2) # グリッド線と外枠を黒で描画
img_without_grid = cv2.bitwise_and(img, mask)
# 画像からデータポイントを抽出
for i in range(w):
line = img_without_grid[:, i]
edge = [j for j in range(h - 1) if line[j] != line[j + 1]]
if len(edge) < 1:
val = 0
elif len(edge) == 1:
if edge[0] > h / 2:
val = 0
else:
val = h
else:
val = h - sum(edge) / 2
point = [i + 1, val]
profile.append(point)
# 座標変換を行う
y = max(profile, key=lambda p: p[1])[1]
for q in range(w):
profile[q][0] = profile[q][0] * (x_max - x_min) / w + x_min
profile[q][1] = (profile[q][1] * (y_max - y_min) / y) + y_min
return profile
# 抽出したデータポイントを取得
data_points = get_profile()
# 抽出したデータポイントのx, y座標を取得
x_coords = [point[0] for point in data_points if x_min <= point[0] <= x_max and y_min <= point[1] <= y_max]
y_coords = [point[1] for point in data_points if x_min <= point[0] <= x_max and y_min <= point[1] <= y_max]
# オリジナルの画像を表示
plt.figure(figsize=(10, 6))
original_img = cv2.imread(image)
original_img_rgb = cv2.cvtColor(original_img, cv2.COLOR_BGR2RGB)
plt.imshow(original_img_rgb)
plt.title('Original Image')
plt.grid(False)
plt.show()
# 抽出したトルク曲線を表示
plt.figure(figsize=(10, 6))
plt.scatter(x_coords, y_coords, color='blue', marker='o', label='Torque Curve')
plt.title('Scatter Plot of Extracted Torque Curve (Ignoring Grid Lines and Outline)')
plt.xlabel('X座標')
plt.ylabel('Y座標')
plt.legend()
plt.grid(True)
plt.show()
パラメータ値のkやthを変えて色々トライしてみましたが,中々に難しいですね.
前回よりは,ましか...
やっぱり行き着くところは...