当前位置:   article > 正文

基于opencv、matlab的多十字靶标的自动识别 与 模板匹配多次匹配的问题_opencv 十字型 匹配

opencv 十字型 匹配

       相机标定时常会使用标定板进行标定,常用的标定法有张正友老师的平板标定,常用的标定板有棋盘标定板和圆盘标定板,但是很多地方使用TSAI两步标定法时会使用自制的标定靶标吗,例如我们采用的按规则排序的十字靶标,拍摄得到的实物如下:

方法一:  Hough 直线检测求交点

      为了得到各十字中心的坐标,常用的方法为使用hough直线检测,得到横竖的所有直线的表达式并通过交点解算来得到交点的坐标,这一块我也做了,但是事实来看,需要多次试探得到合适的阈值等参数,也就是说程序的泛化性比较差,这应该也是我代码写的不好,但是实在找不到好的方法,因为阈值参数的选取确实是得调整的,而且同一标定板上下的明暗是会有差异的,后面我也是为了避免后面的点的获取,只选了前部分识别度较高的十字,但是因为是作为标定的输入,这么多点数已经够了。当然也可以微调参数得到所有的交点,但是我这个标定板有一个十字因为制作时打错了,所以我人为滤掉这一行;下面是我使用MATLAB给出的方法:

  1. front = imread('a.bmp');
  2. back = imread('a_back.bmp');
  3. %img = imread('cali.bmp');
  4. img = front - back;
  5. img_gray = rgb2gray(img);
  6. %% 获取行
  7. thresh = graythresh(img_gray);
  8. B = im2bw(img_gray, thresh);
  9. B = bwmorph(B, 'skel', 1); % 骨架提取
  10. B = bwmorph(B, 'spur', 2); % 去毛刺
  11. [H, theta, rho] = hough(B, 'Theta', 30:0.03:89);
  12. peaks = houghpeaks(H, 14);
  13. rows = houghlines(B, theta, rho, peaks);
  14. imshow(B), hold on;
  15. temp = [];
  16. row_line = [];
  17. for k = 1:length(rows)
  18. temp = [temp; rows(k).point1];
  19. end
  20. [temp, I] = sort(temp, 1, 'ASCEND');
  21. for k = 1 : 6 % 希望的行数
  22. xy = [rows(I(k, 2)).point1, rows(I(k, 2)).point2];
  23. plot([xy(1,1), xy(1, 3)], [xy(1,2), xy(1,4)], 'LineWidth', 2, 'Color', 'green');%画出线段
  24. plot(xy(1,1), xy(1,2), 'x', 'LineWidth', 2, 'Color', 'yellow');%起点
  25. plot(xy(1,3), xy(1,4), 'x', 'LineWidth', 2, 'Color', 'red');%终点
  26. row_line = [row_line; xy]; %[startX startY endX endY]
  27. end
  28. %% 获取列
  29. thresh = graythresh(img_gray);
  30. B = im2bw(img_gray, thresh);
  31. %B = bwmorph(B, 'skel', 1); % 骨架提取
  32. %B = bwmorph(B, 'spur', 1); % 去毛刺
  33. [H, theta, rho] = hough(B, 'Theta',-30:0.03:30);
  34. peaks = houghpeaks(H, 7);
  35. columns = houghlines(B, theta, rho, peaks);
  36. %imshow(B),
  37. hold on;
  38. temp = [];
  39. column_line = [];
  40. for k = 1:length(columns)
  41. temp = [temp; columns(k).point1];
  42. end
  43. [temp, I] = sort(temp, 1, 'ASCEND');
  44. for k = 1 : 4 % 希望的列数
  45. xy = [columns(I(k, 1)).point1, columns(I(k, 1)).point2];
  46. plot([xy(1,1), xy(1, 3)],[xy(1,2), xy(1,4)],'LineWidth',2,'Color','green');%画出线段
  47. plot(xy(1,1),xy(1,2),'x','LineWidth',2,'Color','yellow');%起点
  48. plot(xy(1,3),xy(1,4),'x','LineWidth',2,'Color','red');%终点
  49. column_line = [column_line; xy]; %[startX startY endX endY]
  50. end
  51. %% 获取交点像素坐标
  52. intersection = [];
  53. line = [row_line; column_line];
  54. for i = 1 : length(line) - 1
  55. p1 = line(i, :);
  56. k1 = (p1(2) - p1(4)) / (p1(1) - p1(3));
  57. b1 = p1(2) - k1*p1(1);
  58. for j = i+1 : length(line)
  59. p2 = line(j, :);
  60. k2 = (p2(2)-p2(4))/(p2(1)-p2(3));
  61. b2 = p2(2)-k2*p2(1);
  62. %求两直线交点
  63. x = -(b1-b2) / (k1-k2);
  64. y = -(-b2*k1+b1*k2) / (k1-k2);
  65. %判断交点是否在两线段上 可能存在斜率十分相近导致上式分母接近零而误解
  66. if min(p1(1),p1(3)) <= x && x <= max(p1(1),p1(3)) && ...
  67. min(p1(2),p1(4)) <= y && y <= max(p1(2),p1(4)) && ...
  68. min(p2(1),p2(3)) <= x && x <= max(p2(1),p2(3)) && ...
  69. min(p2(2),p2(4)) <= y && y <= max(p2(2),p2(4))
  70. plot(x,y,'.');
  71. intersection = [intersection; [x, y]]; %依次第一至最后行 与 第一至最后列
  72. end
  73. end
  74. end

得到的结果如下:

   分别为所有行、所有列;设置的六行四列的交点,对应交点其实已经求出,并在四图中标出(红点)

          

 

方法二:   OpenCV 轮廓查找和模板匹配

使用OpenCV对图像进行处理,经过简单处理后,先进行轮廓查找找到所有的十字轮廓,其中很可能混入因阈值不当引入的噪点的轮廓,但是我们可以使用轮廓面积来约束,找到适中大小的轮廓,其实就是某个十字靶标的图案,将此作为模板来对对象进行查找,考虑会出现多次查找的问题,就是对某一轮廓稍微左右移动得到的轮廓依旧匹配度较高,因此会被识别为模板,但是又不能提高识别度,识别度要求一旦提高则会丢失很多不是很请清楚的目标,故在稍微降低识别度的情况下(此时肯定存在重复识别的问题),比较两轮廓的相对距离来剔除重复识别的对象,主要是先将所有相近的目标全部赋值为第一个目标(此处可能略粗糙,也是误差产生的地方)。然后剔除相同的目标,在对所得所有点按照空间实际顺序进行排列以便对应实际的世界坐标(标定的时候需要);代码如下:

  1. import numpy as np
  2. import cv2
  3. import os
  4. GREEN = (0, 255, 0)
  5. RED = (0,0,255)
  6. filename = 'pixelCoordinate.txt'
  7. # **** Basic processing of the original image and extract all contours ****
  8. img = cv2.imread('cali.bmp')
  9. imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
  10. ret,thresh = cv2.threshold(imgray,30,255,0)
  11. image, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
  12. # *********** Find an appropriate contour for the template **********
  13. for cnt in contours:
  14. if cv2.contourArea(cnt) > 120:
  15. (x,y,w,h) = cv2.boundingRect(cnt)
  16. template=imgray[y:y+h, x:x+w]
  17. rootdir=("C:/Users/Administrator/Desktop/cali/")
  18. if not os.path.isdir(rootdir):
  19. os.makedirs(rootdir)
  20. cv2.imwrite( rootdir + "template.bmp",template)
  21. break
  22. # ************ Find all matched contours ************
  23. w, h = template.shape[::-1]
  24. res = cv2.matchTemplate(imgray, template, cv2.TM_CCOEFF_NORMED)
  25. threshold = 0.75
  26. point = []
  27. point_temp = []
  28. loc = np.where(res >= threshold)
  29. for pt in zip(*loc[::-1]):
  30. point.append([pt[0], pt[1]])
  31. length = len(point)
  32. print(' Before Processing: ' + str(length))
  33. # **** Assign the corresponding point of a similar template to one of them ******
  34. i = 0
  35. while(i < length):
  36. for j in range(i + 1, length):
  37. if ( np.abs(point[j][0] - point[i][0]) < 4 and np.abs(point[j][1] - point[i][1]) < 4):
  38. point[j] = point[i]
  39. i = i + 1
  40. # ***************** Eliminate similarities *******************
  41. for i in point:
  42. if i not in point_temp:
  43. point_temp.append(i)
  44. print(' After Processing: ' + str(len(point_temp)))
  45. # ********** In order from left to right, from top to bottom ***********
  46. point_temp.sort(key = lambda x:x[0])
  47. for i in range(0, 92, 14):
  48. point_temp[i : i+14].sort(key = lambda x:x[1])
  49. # ***************** Display and save the results **********************
  50. if os.path.exists(filename):
  51. os.remove(filename)
  52. for index in range(len(point_temp)):
  53. cv2.rectangle(img, tuple(point_temp[index]), (point_temp[index][0] + w, point_temp[index][1] + h), RED, 1)
  54. x = int(point_temp[index][0] + w/2)
  55. y = int(point_temp[index][1] + h/2)
  56. with open(filename, 'a') as file:
  57. file.write(str(x) + ' ' + str(y) + "\n")
  58. cv2.circle(img, (x, y), 0, GREEN, 0)
  59. cv2.imshow('Result', img)
  60. cv2.imwrite('Result.bmp', img)

结果如下:

  

总结:

       按照最后结果来看,方法一得到的精度更高,但是会人为调整较多参数,适应性差;方法二的精度没有第一个高,但是适应性比较强,这就比较尴尬,后面有需要会在精度方面做调整,毕竟这个方法还是比较简洁;

      各位有啥好的方案欢迎评论交流!!!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/50798
推荐阅读
相关标签
  

闽ICP备14008679号