本文將介紹如何使用python對視覺進行識別并獲取坐標,主要涵蓋圖像預處理、目標檢測等技術方面,希望對需要使用此類技術的讀者提供一些參考和幫助。
一、圖像預處理
在進行圖像處理前,需要先對圖像進行預處理,以便更好地提取目標信息。以下是一些圖像預處理常用的方法:
1、顏色空間轉換
img = cv2.imread('example.jpg')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
2、圖像濾波
img = cv2.imread('example.jpg')
img_blur = cv2.GaussianBlur(img, (3,3), 0)
3、圖像二值化
img = cv2.imread('example.jpg')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, img_thresh = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
二、目標檢測
目標檢測可以大致分為兩種方法:基于特征的方法和基于深度學習的方法。以下是常用的目標檢測方法:
1、基于特征的方法
img = cv2.imread('example.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
template = cv2.imread('template.jpg',0)
res = cv2.matchTemplate(gray,template,cv2.TM_CCOEFF_NORMED)
threshold = 0.95
loc = np.where(res>=threshold)
for pt in zip(*loc[::-1]):
cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)
cv2.imshow('img',img)
cv2.waitKey(0)
2、基于深度學習的方法
import numpy as np
import tensorflow as tf
from PIL import Image
model = tf.keras.models.load_model('model.h5')
# 讀取圖像
img = Image.open('example.jpg')
img = img.resize((224, 224))
img_array = np.array(img)
img_array = np.expand_dims(img_array, axis=0)
# 預測坐標
prediction = model.predict(img_array)
x = prediction[0][0] * img.width
y = prediction[0][1] * img.height
三、坐標獲取
通過目標檢測,我們可以獲取到目標在圖像中的位置,接下來需要將其轉化為實際坐標。以下是一些常用的坐標獲取方法:
1、通過攝像機參數計算
K = np.array([[fx, 0, cx],
[0, fy, cy],
[0, 0, 1]])
rvec, tvec = cv2.solvePnP(objpoints, imgpoints, K, None)
tvec = tvec.flatten()
2、手動標定
def get_mouse_pos(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONUP:
print("Mouse Clicked at: ({}, {})".format(x, y))
cv2.namedWindow("image")
cv2.setMouseCallback("image", get_mouse_pos)
cv2.imshow("image", img)
cv2.waitKey(0)
四、總結
通過本文的介紹,我們可以看到python在視覺識別坐標方面提供了許多強大的工具和方法。通過圖像預處理、目標檢測和坐標獲取,我們可以在實際項目中實現更加精細的控制和交互。