云计算期末大作业 论文图像复用的机器自动检查 魏如蓝 10172100262
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

169 lines
5.9 KiB

3 years ago
  1. from __future__ import print_function
  2. import cv2
  3. import numpy as np
  4. import os
  5. from flask import render_template
  6. import zipfile
  7. MAX_MATCHES = 500
  8. GOOD_MATCH_PERCENT = 0.15
  9. class feat:
  10. def call_feature_extraction_1(self, folder_path, list, index, tmp):
  11. # 按相似度排序
  12. list = sorted(list, key=(lambda x: [x[2], x[5]]),reverse=True)
  13. print(list)
  14. print('---------------')
  15. print(index)
  16. for i in range(int(index/10)):
  17. # 取第一组比较并返回
  18. refFilename = list[i][0]
  19. # imgname1 = '/home/Jupyterlab/wrl/pic/xiagao/pic/11.jpeg'
  20. print("Reading reference image : ", refFilename)
  21. imReference = cv2.imread(refFilename, cv2.IMREAD_COLOR)
  22. imFilename = list[i][1]
  23. # imgname2 = '/home/Jupyterlab/wrl/pic/xiagao/pic/12.jpeg'
  24. print("Reading image to align : ", imFilename);
  25. im = cv2.imread(imFilename, cv2.IMREAD_COLOR)
  26. print(refFilename)
  27. print(imFilename)
  28. print(folder_path[7:])
  29. p1 = refFilename.rfind('/')
  30. name1 = refFilename[p1:-4]
  31. print(name1)
  32. p2 = imFilename.rfind('/')
  33. name2 = imFilename[p2 + 1:]
  34. print(name2)
  35. # Write aligned image to disk.
  36. outFilename = "output/" + folder_path[7:]
  37. pre = os.getcwd()
  38. print("Saving aligned image : ", outFilename)
  39. print("Aligning images ...")
  40. # Registered image will be resotred in imReg.
  41. # The estimated homography will be stored in h.
  42. imReg, h, img5 = feat().alignImages(im, imReference)
  43. if (str(img5) == 'white'):
  44. print('white')
  45. # continue
  46. else:
  47. print(outFilename)
  48. # imgwrite需要建好路径!!!!!!
  49. if not os.path.exists(outFilename):
  50. os.makedirs(outFilename)
  51. outFilename1 = outFilename + name1 + name2
  52. cv2.imwrite(outFilename1, img5)
  53. # continue
  54. outFullName = feat.zipDir(outFilename)
  55. pre1 = "/home/wwwroot/default/" + outFilename + ".zip"
  56. # return str(pre) + '/' + outFilename
  57. # return pre1
  58. return outFullName
  59. def alignImages(self, im1, im2):
  60. # Convert images to grayscale
  61. im1Gray = cv2.cvtColor(im1, cv2.COLOR_BGR2GRAY)
  62. im2Gray = cv2.cvtColor(im2, cv2.COLOR_BGR2GRAY)
  63. # Detect ORB features and compute descriptors.
  64. orb = cv2.ORB_create(MAX_MATCHES)
  65. keypoints1, descriptors1 = orb.detectAndCompute(im1Gray, None)
  66. keypoints2, descriptors2 = orb.detectAndCompute(im2Gray, None)
  67. if keypoints1 and keypoints2:
  68. # Match features.
  69. matcher = cv2.DescriptorMatcher_create(cv2.DESCRIPTOR_MATCHER_BRUTEFORCE_HAMMING)
  70. matches = matcher.match(descriptors1, descriptors2, None)
  71. # Sort matches by score
  72. matches.sort(key=lambda x: x.distance, reverse=False)
  73. # Remove not so good matches
  74. numGoodMatches = int(len(matches) * GOOD_MATCH_PERCENT)
  75. matches = matches[:numGoodMatches]
  76. # Draw top matches
  77. imMatches = cv2.drawMatches(im1, keypoints1, im2, keypoints2, matches, None)
  78. cv2.imwrite("matches.jpg", imMatches)
  79. # Extract location of good matches
  80. points1 = np.zeros((len(matches), 2), dtype=np.float32)
  81. points2 = np.zeros((len(matches), 2), dtype=np.float32)
  82. for i, match in enumerate(matches):
  83. points1[i, :] = keypoints1[match.queryIdx].pt
  84. points2[i, :] = keypoints2[match.trainIdx].pt
  85. if (points1.size == 0) or (points2.size == 0):
  86. return 'white', 'white', 'white'
  87. # Find homography
  88. h, mask = cv2.findHomography(points1, points2, cv2.RANSAC)
  89. # Use homography
  90. height, width, channels = im2.shape
  91. im1Reg = cv2.warpPerspective(im1, h, (width, height))
  92. img1 = cv2.drawKeypoints(im1, keypoints1, im1, color=(255, 0, 255))
  93. img2 = cv2.drawKeypoints(im2, keypoints2, im2, color=(255, 0, 255))
  94. img5 = cv2.drawMatches(img1, keypoints1, img2, keypoints2, matches, None, flags=2)
  95. return im1Reg, h, img5
  96. else:
  97. return 'white', 'white', 'white'
  98. def return_img_stream(self, img_local_path):
  99. # """
  100. # 工具函数:
  101. # 获取本地图片流
  102. # :param img_local_path:文件单张图片的本地绝对路径
  103. # :return: 图片流
  104. # """
  105. import base64
  106. img_stream = ''
  107. with open(img_local_path, 'r') as img_f:
  108. img_stream = img_f.read()
  109. img_stream = base64.b64encode(img_stream)
  110. return img_local_path
  111. def zipDir(dirpath):
  112. """
  113. :param dirpath:
  114. :param outFullName: +xxxx.zip
  115. :return:
  116. """
  117. outFullName = "/home/wwwroot/default/" + dirpath[21:] + ".zip"
  118. outFullName1 = "http://106.75.226.23/" + dirpath[21:] + ".zip"
  119. # if not os.path.exists(outFullName):
  120. # os.makedirs(outFullName)
  121. zip = zipfile.ZipFile(outFullName, "w", zipfile.ZIP_DEFLATED)
  122. for path, dirnames, filenames in os.walk(dirpath):
  123. # 去掉目标跟路径,只对目标文件夹下边的文件及文件夹进行压缩
  124. fpath = path.replace(dirpath, '')
  125. for filename in filenames:
  126. zip.write(os.path.join(path, filename), os.path.join(fpath, filename))
  127. zip.close()
  128. return outFullName1
  129. # im1 = '/Users/wrl/Desktop/test0506/pic/2303.png'
  130. # im2 = '/Users/wrl/Desktop/test0506/pic/2304.png'
  131. # img1 = cv2.imread(im1, cv2.IMREAD_COLOR)
  132. # img2 = cv2.imread(im2, cv2.IMREAD_COLOR)
  133. # imReg, h, img5 =feat().alignImages(img1,img2)