SHARE
TWEET

Untitled

a guest Mar 23rd, 2019 84 in 60 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import cv2 #графический модуль opencv
  2. import pylab #модуль операций матмоделирования
  3. import numpy as np #модуль операций над матрицами
  4. from os import listdir #список файлов в папке
  5. from os.path import isfile, join #методы проверки файла и соединения с  файлом
  6. import statistics
  7. from sklearn.metrics import classification_report
  8. from matplotlib import pyplot as plt
  9. #-------------ПОЛУЧИЛИ ИЗОБРАЖЕНИЕ И ВЫВЕЛИ ЕГО--------------------------
  10. mypath='C:/Users/inet/Desktop/part_start'
  11. onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
  12. img = np.empty(len(onlyfiles), dtype=object)
  13. for n in range(0, len(onlyfiles)):
  14.   img[n] = cv2.imread(join(mypath, onlyfiles[n]))
  15. #---------------------ПОКРАСИЛИ В СЕРОЕ-----------------------------------
  16. lab = cv2.cvtColor(img[n], cv2.COLOR_BGR2GRAY)
  17. cv2.imshow("GreyColor", lab)
  18. cv2.waitKey(5000)
  19. #---------------------НАРИСОВАЛИ ГРАФИК-----------------------------------
  20. values = []
  21. for c in range(lab.shape[1]):
  22.     count = 255
  23.     for r in range(lab.shape[0]):
  24.         count += lab[r][c]
  25.     values.append(count / lab.shape[0])
  26. pylab.figure()
  27. pylab.ylabel('Average Luminance')
  28. pylab.xlabel('X axis')
  29. pylab.plot(values, 'k-')
  30. pylab.show()
  31. #---------------------НАПЕЧАТАЛИ СРЕДНЕЕ ИЗ МАССИВА ПИКСЕЛЕЙ--------------------
  32. R = int(np.mean(values))
  33. print(R)
  34. #---------------------СТАНДАРТИЗИРОВАЛИ ИЗОБРАЖЕНИЕ--------------------
  35. varianceMatrix = np.zeros((2, 512*512), dtype=np.uint8)
  36. varianceMatrix[0, :] = 255
  37. varianceMatrix[:, 0] = 0
  38. Des = int(np.std(varianceMatrix))
  39. print(Des)
  40. std = np.sqrt(Des)
  41. standardized_images_out = (lab - R) / (0.5*Des)
  42. cv2.imshow("lab.png", standardized_images_out)
  43. blur = cv2.blur(standardized_images_out, (7, 7))
  44.  
  45. plt.subplot(121), plt.imshow(standardized_images_out), plt.title('Original')
  46. plt.xticks([]), plt.yticks([])
  47. plt.subplot(122), plt.imshow(blur), plt.title('Blurred')
  48. plt.xticks([]), plt.yticks([])
  49. plt.show()
  50. #---------------------------ПРОШЛИСЬ ПОРОГОМ--------------------------
  51.  
  52. #imggray = cv2.cvtColor(lab, cv2.COLOR_BGR2GRAY)
  53. ret, thresh = cv2.threshold(lab, 127, 255, cv2.THRESH_BINARY)
  54.  
  55. #---------------------------НАРИСОВАЛИ КОНТУР--------------------------
  56. image_prepared = cv2.GaussianBlur(thresh, (5, 5), 0)
  57. _, contours, hierarchy = cv2.findContours(image_prepared.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  58. img2 = cv2.drawContours(thresh, contours, -1, (0, 0, 0), 3, cv2.LINE_AA, hierarchy, 1)
  59. cv2.imshow('Example', img2)
  60. cv2.waitKey(5000)
  61. #---------------------------МАТ. МОРФОЛОГИЯ--------------------------
  62. kernel = np.ones((5, 5), np.uint8)
  63. #closing = cv2.morphologyEx(img2, cv2.MORPH_CLOSE, kernel, 1)
  64. erosion = cv2.erode(img2, kernel, 1)
  65. dilation = cv2.dilate(erosion, kernel, 2)
  66. opening = cv2.morphologyEx(dilation, cv2.MORPH_OPEN, kernel, 2)
  67. cv2.imshow('Erosion', opening)
  68. cv2.waitKey(5000)
  69. #------------ВЫДЕЛЕНИЕ МЕНЬШИИХ ОБЛАСТЕЙ И ИХ ОБРЕЗКА--------------------------
  70. opening, contours, hierarchy = cv2.findContours(opening.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  71. Max = 0
  72. pos = 0
  73. for idx in range(0, len(contours)):
  74.     cnt = np.array(contours[idx])
  75.     cv2.drawContours(opening, [cnt], 0, 0, -1)
  76.     area = cv2.contourArea(contours[idx])
  77.     if area > Max:
  78.         pos = idx
  79.         Max = area
  80. maxContour = np.array(contours[pos])
  81. cv2.drawContours(opening, [maxContour], 0, 255, -1)
  82. cv2.imshow('RoiImg', opening)
  83. cv2.waitKey(5000)
  84. #---------------------------ЗАПИСАЛИ В ПАПКУ--------------------------
  85. mypath='C:/Users/inet/Desktop/part_start_late'
  86. cv2.imwrite(join(mypath, 'test.png'), opening)
  87. cv2.waitKey(10000)
  88. #---------------------------ПОЛУЧИЛИ ИЗ ПАПКИ--------------------------
  89. onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
  90. img = np.empty(len(onlyfiles), dtype=object)
  91. for n in range(0, len(onlyfiles)):
  92.   img[n] = cv2.imread(join(mypath, onlyfiles[n]),  cv2.IMREAD_GRAYSCALE)
  93. cv2.imshow("End", img[n])
  94. cv2.waitKey(5000)
  95. test = img[n]
  96. #--------------------ПОСЧИТАЛИ ЧИСЛО ПИКСЕЛЕЙ--------------------------
  97. n_white_pix = cv2.countNonZero(test)
  98. print('Number of white pixels:', n_white_pix)
  99. size = test.size
  100. n_black_pix = size - n_white_pix
  101. print('Number of black pixels:', n_black_pix)
  102. #---------------------Считаем число пикселей в финальной выборке-------------
  103. mypath ='C:/Users/inet/Desktop/part_finish'
  104. onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
  105. img = np.empty(len(onlyfiles), dtype=object)
  106. for n in range(0, len(onlyfiles)):
  107.   img[n] = cv2.imread(join(mypath, onlyfiles[n]),  cv2.IMREAD_GRAYSCALE)
  108. test = img[n]
  109. n_white_pix_0 = cv2.countNonZero(test)
  110. print('Number of white pixels:', n_white_pix)
  111. size = test.size
  112. n_black_pix_0 = size - n_white_pix_0
  113. print('Number of black pixels:', n_black_pix)
  114. #---------------------СчЧИТАЕМ МЕТРИКИ-------------
  115. correct = [[n_white_pix], [n_black_pix]]
  116. predicted = [[n_white_pix_0], [n_black_pix_0]]
  117. correct_flat = [item for sublist in correct for item in sublist]
  118. predicted_flat = [item for sublist in predicted for item in sublist]
  119.  
  120. print(classification_report(correct_flat, predicted_flat))
  121.  
  122. cv2.destroyAllWindows()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top