CrossColor.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. def cmpPicTotal(picpath1):
  62. images = getPartImage(picpath1)
  63. if len(images) != 8:
  64. print "彩色分离异常"
  65. else:
  66. for image in images:
  67. wight = image.shape[1]
  68. hight = image.shape[0]
  69. B, G, R = cv.split(image)
  70. sum_B = 0
  71. sum_G = 0
  72. sum_R = 0
  73. for x in range(0, hight, 1):
  74. for y in range(0, wight, 1):
  75. sum_B = sum_B + B[x][y]
  76. sum_G = sum_G + G[x][y]
  77. sum_R = sum_R + R[x][y]
  78. avg_B = sum_B / (wight * hight)
  79. avg_G = sum_G / (wight * hight)
  80. avg_R = sum_R / (wight * hight)
  81. for x in range(0, hight, 1):
  82. for y in range(0, wight, 1):
  83. 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:
  84. return False
  85. else:
  86. return True