CrossColor.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #coding=utf-8
  2. '''颜色串色检测'''
  3. import cv2 as cv
  4. import numpy as np
  5. #裁剪图片
  6. def cutImage(img_addr):
  7. img = cv.imread(img_addr)
  8. img_arr = np.array(img)
  9. hight = img_arr.shape[0]
  10. wight = img_arr.shape[1]
  11. dest_img = img_arr[hight/2+20:hight,0:wight,:]
  12. return dest_img
  13. #得到横坐标点
  14. def getSpot(dest_img):
  15. edge_img_rgb = cv.convertScaleAbs(cv.Sobel(dest_img,cv.CV_16S,1,0))
  16. edge_img_gray = cv.cvtColor(edge_img_rgb,cv.COLOR_BGR2GRAY)
  17. _,edge_img = cv.threshold(edge_img_gray,50,255,cv.THRESH_BINARY)
  18. #做一条水平线
  19. tumple1=[]
  20. tumple = []
  21. for y in range(0,edge_img.shape[1],1):
  22. if edge_img[70][y] == 255:
  23. tumple1.append(y)
  24. tumple.append(y)
  25. count = 0
  26. for i in range(0,len(tumple1)):
  27. if i != len(tumple1)-1:
  28. if tumple1[i+1] - tumple1[i]>15:
  29. if count == 0:
  30. tumple.insert(i+1,".")
  31. else :
  32. tumple.insert(count+i+1,".")
  33. count= count +1
  34. tumple.insert(len(tumple),".")
  35. lines =[]
  36. recode = 0
  37. for i in range(0,len(tumple),1):
  38. if tumple[i] == "." :
  39. if recode == 0:
  40. temp_arr = tumple[recode:i]
  41. recode = i
  42. else:
  43. temp_arr = tumple[recode+1:i]
  44. recode = i
  45. lines.append(sum(temp_arr)/len(temp_arr))
  46. return lines
  47. #输入图片地址,返回拆分图片
  48. def getPartImage(img_addr):
  49. dest_img = cutImage(img_addr)
  50. lines = getSpot(dest_img)
  51. images = []
  52. for i in range(0,len(lines)):
  53. if i ==0:
  54. images.append(dest_img[0:dest_img.shape[0],0:lines[i]-5,:])
  55. else:
  56. if i == len(lines)-1:
  57. images.append(dest_img[0:dest_img.shape[0],lines[i]+5:dest_img.shape[1]-5,:])
  58. images.append(dest_img[0:dest_img.shape[0],lines[i-1]+5:lines[i]-5,:])
  59. return images
  60. # 对外提供方法.函数准确度不够。
  61. # 废弃
  62. def cmpPicTotal(picpath1):
  63. images = getPartImage(picpath1)
  64. if len(images) != 8:
  65. print "彩色分离异常"
  66. else:
  67. for image in images:
  68. wight = image.shape[1]
  69. hight = image.shape[0]
  70. B, G, R = cv.split(image)
  71. sum_B = 0
  72. sum_G = 0
  73. sum_R = 0
  74. for x in range(0, hight, 1):
  75. for y in range(0, wight, 1):
  76. sum_B = sum_B + B[x][y]
  77. sum_G = sum_G + G[x][y]
  78. sum_R = sum_R + R[x][y]
  79. avg_B = sum_B / (wight * hight)
  80. avg_G = sum_G / (wight * hight)
  81. avg_R = sum_R / (wight * hight)
  82. for x in range(0, hight, 1):
  83. for y in range(0, wight, 1):
  84. if abs(image[x][y][0] - avg_B)>20 or abs(image[x][y][1] - avg_G) >20 or abs(image[x][y][2] -avg_R) >20:
  85. return False
  86. else:
  87. return True