import cv2 as cv
import numpy as np
import time
def xunji():
cap = cv.VideoCapture(0, cv.CAP_DSHOW)
cap.set(3, 600)
cap.set(4, 600)
if cap.isOpened():
while 1:
ret, frame = cap.read()
res = cv.resize(frame, None, fx=0.5, fy=0.5)
cv.imshow("res", res)
# 颜色空间转换
res1 = cv.cvtColor(res, cv.COLOR_BGR2GRAY)
res2 = cv.cvtColor(res, cv.COLOR_BGR2HSV)
# 图像阈值设置
ret0, thresh1 = cv.threshold(res1, 80, 255, cv.THRESH_BINARY)
# 高斯滤波
blur = cv.medianBlur(thresh1, 5)
# 形态学运算
kernel = np.ones((5, 5), np.uint8)
cvOpen = cv.morphologyEx(blur, cv.MORPH_OPEN, kernel) # 开运算
cv.imshow("cvOpen", cvOpen)
# kirsch算子
m1 = np.array([[5, 5, 5], [-3, 0, -3], [-3, -3, -3]])
m2 = np.array([[-3, 5, 5], [-3, 0, 5], [-3, -3, -3]])
m3 = np.array([[-3, -3, 5], [-3, 0, 5], [-3, -3, 5]])
m4 = np.array([[-3, -3, -3], [-3, 0, 5], [-3, 5, 5]])
m5 = np.array([[-3, -3, -3], [-3, 0, -3], [5, 5, 5]])
m6 = np.array([[-3, -3, -3], [5, 0, -3], [5, 5, -3]])
m7 = np.array([[5, -3, -3], [5, 0, -3], [5, -3, -3]])
m8 = np.array([[5, 5, -3], [5, 0, -3], [-3, -3, -3]])
filterlist = [m1, m2, m3, m4, m5, m6, m7, m8] # 将各个方向的卷积核放到一起便于统一操作
filtered_list = np.zeros((8, cvOpen.shape[0], cvOpen.shape[1])) # 建立三维数组,第0维表示各个方向卷积后的值
for k in range(8):
out = cv.filter2D(cvOpen, cv.CV_16S, filterlist[k]) # 自定义卷积,其实里面的步骤跟Sobel算子是差不多的
filtered_list[k] = out
final = np.max(filtered_list, axis=0) # 取八个方向中的最大值,也就是取第0维的最大值作为图像该点,滤波之后的新的像素值
final[np.where(final >= 255)] = 255 # 令像素值大于255的点等于255
final[np.where(final < 255)] = 0 # 令像素值小于255的点等于0
cv.imshow("final", final)
# 判断
try:
m = []
w = []
p = []
height = int(final.shape[0])
width = int(final.shape[1])
i = 0
while i < height-1:
n = []
if len(m) < 20:
for j in range(10, width-1):
if final[i, j] == final[i, j+1] and final[i, j+1] == 0:
j += 2
elif final[i, j] != final[i, j+1] and final[i, j + 1] == 255:
n.append(j+1)
# print(n)
if len(n) != 0:
w.append(n)
m.append(len(n))
i += 2
a = 0
t = 1
for k in range(len(m)):
if m[k] == 0:
p.append(0)
if m[k] == 1:
p.append((2*w[k][0] + 40)/2)
if m[k] == 2:
p.append((w[k][0] + w[k][1])/2)
if m[k] == 3:
p.append((w[k][0] + 40)/2)
# if 60 < sum(m) <= 80 and a == 0:
# if t == 1:
# p.append((w[k][0] + w[k][1]) / 2)
# elif t == 2:
# p.append((w[k][3] + w[k][2]) / 2)
# elif t == 3:
# p.append((w[k][0] + w[k][1]) / 2)
# elif t == 4:
# p.append((w[k][0] + w[k][1]) / 2)
# a = 1
# elif m[k] == 2 and a:
# t += 1
# a = 0
p.remove(max(p))
p.remove(min(p))
print("距离中心:%.2f" %(165-sum(p)/(len(p)-1)))
except Exception as e:
print(e)
low_yellow = np.array([26, 43, 46])
high_yellow = np.array([34, 255, 255])
mask = cv.inRange(res2, low_yellow, high_yellow)
open = cv.morphologyEx(mask, cv.MORPH_OPEN, kernel)
edges = cv.Canny(open, 10, 20)
cnts, _ = cv.findContours(
edges, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE)
if len(cnts) > 0:
break
cv.imshow("mask", edges)
if cv.waitKey(1) == ord('q'):
break
cap.release()
cv.destroyAllWindows()
if __name__ == "__main__":
xunji()
|