Map Inference in the Face of Noise and Disparity代码重现遇到的问题(持续更新....)

旧城等待, 2023-07-18 02:37 94阅读 0赞

目录

    1. 论文链接
    1. 安装环境
    1. 遇到的问题和解决方法
    • 3.1 第一步运行kde.py
    • 3.2 第二步运行skeleton.py
      • 3.2.1 ImportError: No module named pyximport***
      • 3.2.2 Pychorm提示Unresolved reference 导入模块报错
      • 3.2.3 ImportError: Building module subiterations failed: [‘DistutilsPlatformError: Unable to find vcvarsall.bat\n’](生成模块子迭代失败
      • 3.2.4 ImportError: Building module subiterations failed: [“CompileError: command ‘C:\\\\Users\\\\87792\\\\AppData\\\\Local\\\\Programs\\\\Common\\\\Microsoft\\\\Visual C++ for Python\\\\9.0\\\\VC\\\\Bin\\\\amd64\\\\cl.exe’ failed with exit status 2\n”]

1. 论文链接

Map Inference in the Face of Noise and Disparity
代码下载地址

2. 安装环境

python 2.7.15 win64位
Opencv 2.4.13 win64位 (安装过程可参考windows平台下python安装opencv,即实现import cv2功能)
pycharm 2019.3.3 win64位(来源微信公众号PyCharm2019【中文版】安装教程)

3. 遇到的问题和解决方法

3.1 第一步运行kde.py

  1. #coding:utf-8
  2. import cv2
  3. import cv2.cv as cv
  4. from math import atan2, sqrt, ceil, pi, fmod
  5. import sys, getopt, os
  6. from location import TripLoader
  7. from pylibs import spatialfunclib
  8. from itertools import tee, izip
  9. import sqlite3
  10. ##
  11. ## important parameters
  12. ##
  13. cell_size = 1 # meters
  14. gaussian_blur = 17
  15. trips_path = "trips/trips_1m/"
  16. def pairwise(iterable):
  17. "s -> (s0,s1), (s1,s2), (s2, s3), ..."
  18. a, b = tee(iterable)
  19. next(b, None)
  20. return izip(a, b)
  21. class KDE:
  22. def __init__(self):
  23. pass
  24. def create_kde_with_trips(self, all_trips):
  25. print "trips path: " + str(trips_path)
  26. print "cell size: " + str(cell_size)
  27. print "gaussian blur: " + str(gaussian_blur)
  28. # flag to save images
  29. save_images = True
  30. sys.stdout.write("\nFinding bounding box... ")
  31. sys.stdout.flush()
  32. min_lat = all_trips[0].locations[0].latitude
  33. max_lat = all_trips[0].locations[0].latitude
  34. min_lon = all_trips[0].locations[0].longitude
  35. max_lon = all_trips[0].locations[0].longitude
  36. for trip in all_trips:
  37. for location in trip.locations:
  38. if (location.latitude < min_lat):
  39. min_lat = location.latitude
  40. if (location.latitude > max_lat):
  41. max_lat = location.latitude
  42. if (location.longitude < min_lon):
  43. min_lon = location.longitude
  44. if (location.longitude > max_lon):
  45. max_lon = location.longitude
  46. print "done."
  47. # find bounding box for data
  48. min_lat -= 0.003
  49. max_lat += 0.003
  50. min_lon -= 0.005
  51. max_lon += 0.005
  52. diff_lat = max_lat - min_lat
  53. diff_lon = max_lon - min_lon
  54. #print min_lat, min_lon, max_lat, max_lon
  55. width = int(diff_lon * spatialfunclib.METERS_PER_DEGREE_LONGITUDE / cell_size)
  56. height = int(diff_lat * spatialfunclib.METERS_PER_DEGREE_LATITUDE / cell_size)
  57. yscale = height / diff_lat # pixels per lat
  58. xscale = width / diff_lon # pixels per lon
  59. # aggregate intensity map for all traces
  60. themap = cv.CreateMat(height,width,cv.CV_16UC1)
  61. cv.SetZero(themap)
  62. ##
  63. ## Build an aggregate intensity map from all the edges
  64. ##
  65. trip_counter = 1
  66. for trip in all_trips:
  67. if ((trip_counter % 10 == 0) or (trip_counter == len(all_trips))):
  68. sys.stdout.write("\rCreating histogram (trip " + str(trip_counter) + "/" + str(len(all_trips)) + ")... ")
  69. sys.stdout.flush()
  70. trip_counter += 1
  71. temp = cv.CreateMat(height,width,cv.CV_8UC1)
  72. cv.SetZero(temp)
  73. temp16 = cv.CreateMat(height,width,cv.CV_16UC1)
  74. cv.SetZero(temp16)
  75. for (orig,dest) in pairwise(trip.locations):
  76. oy = height - int(yscale * (orig.latitude - min_lat))
  77. ox = int(xscale * (orig.longitude - min_lon))
  78. dy = height - int(yscale * (dest.latitude - min_lat))
  79. dx = int(xscale * (dest.longitude - min_lon))
  80. cv.Line(temp, (ox, oy), (dx, dy), (32), 1, cv.CV_AA)
  81. # accumulate trips into themap
  82. cv.ConvertScale(temp,temp16,1,0)
  83. cv.Add(themap,temp16,themap)
  84. lines = cv.CreateMat(height,width,cv.CV_8U)
  85. cv.SetZero(lines)
  86. print "done."
  87. trip_counter = 1
  88. for trip in all_trips:
  89. if ((trip_counter % 10 == 0) or (trip_counter == len(all_trips))):
  90. sys.stdout.write("\rCreating drawing (trip " + str(trip_counter) + "/" + str(len(all_trips)) + ")... ")
  91. sys.stdout.flush()
  92. trip_counter += 1
  93. for (orig, dest) in pairwise(trip.locations):
  94. oy = height - int(yscale * (orig.latitude - min_lat))
  95. ox = int(xscale * (orig.longitude - min_lon))
  96. dy = height - int(yscale * (dest.latitude - min_lat))
  97. dx = int(xscale * (dest.longitude - min_lon))
  98. cv.Line(lines, (ox, oy), (dx, dy), (255), 1, cv.CV_AA)
  99. # save the lines
  100. cv.SaveImage("raw_data.png", lines)
  101. print "done."
  102. #print "Intensity map acquired."
  103. sys.stdout.write("Smoothing... ")
  104. sys.stdout.flush()
  105. # # create the mask and compute the contour
  106. cv.Smooth(themap, themap, cv.CV_GAUSSIAN, gaussian_blur, gaussian_blur)
  107. cv.SaveImage("kde.png", themap)
  108. print "done."
  109. print "\nKDE generation complete."
  110. if __name__ == '__main__':
  111. opts,args = getopt.getopt(sys.argv[1:],"c:b:p:h")
  112. for o,a in opts:
  113. if o == "-c":
  114. cell_size=int(a)
  115. elif o == "-b":
  116. gaussian_blur = int(a)
  117. elif o == "-p":
  118. trips_path = str(a)
  119. elif o == "-h":
  120. print "Usage: kde.py [-c <cell_size>] [-b <gaussian_blur_size>] [-p <trips_path>] [-h]\n"
  121. sys.exit()
  122. k = KDE()
  123. k.create_kde_with_trips(TripLoader.load_all_trips(trips_path))

报错如下:
no module named cv,查了好久才发现是因为自己的opencv版本不匹配,这段代码是用opencv2下写的,而我安装了opencv3所以一开始import cv 便开始报错,后来改成了 import cv2,在77行78行又报 no module named CreateMat 和 no module named SetZero ,后来安装了opencv2后此问题完美解决,opencv2下载链接和安装过程可参见(安装过程可参考windows平台下python安装opencv,即实现import cv2功能)。

3.2 第二步运行skeleton.py

  1. #coding:utf-8
  2. import pyximport; pyximport.install()
  3. import subiterations
  4. import numpy as np
  5. import scipy.ndimage as nd
  6. from scipy.ndimage import imread
  7. from scipy.misc import imsave, toimage
  8. from scipy.stats import threshold
  9. from itertools import izip
  10. from multiprocessing import Process, Manager, cpu_count
  11. from threading import Thread
  12. from scipy.ndimage.morphology import grey_closing
  13. import math
  14. skeleton_images_path = "skeleton_images/"
  15. class GrayscaleSkeleton:
  16. def __init__(self):
  17. pass
  18. def skeletonize(self, image):
  19. image = grey_closing(image, footprint=circle(8), mode='constant', cval=0.0)
  20. image = add_zero_mat(image)
  21. prev_binary_image = np.zeros_like(image)
  22. image_bit_depth = (image.dtype.itemsize * 8) / 2
  23. print "image_bit_depth: " + str(image_bit_depth)
  24. #image_thresholds = range(2**image_bit_depth,-1,-16)
  25. image_thresholds = [2**x for x in range(image_bit_depth, 3, -1)] + range(15, 0, -1)
  26. print "image_thresholds: " + str(image_thresholds)
  27. for curr_threshold in image_thresholds:
  28. print "curr_threshold: " + str(curr_threshold)
  29. curr_thresh_image = threshold(image, curr_threshold)
  30. curr_binary_image = curr_thresh_image.astype(np.bool).astype(np.int)
  31. imsave(skeleton_images_path + "binary_" + str(curr_threshold) + ".png", curr_binary_image)
  32. curr_sum_image = (prev_binary_image + curr_binary_image)
  33. curr_skeleton_image = self.thin_pixels(curr_sum_image)
  34. imsave(skeleton_images_path + "skeleton_" + str(curr_threshold) + ".png", curr_skeleton_image)
  35. print "curr_skeleton max: " + str(curr_skeleton_image.max())
  36. prev_binary_image = curr_skeleton_image
  37. return remove_zero_mat(prev_binary_image)
  38. def thin_pixels(self, image):
  39. pixel_removed = True
  40. neighbors = nd.convolve((image>0).astype(np.int),[[1,1,1],[1,0,1],[1,1,1]],mode='constant',cval=0.0)
  41. fg_pixels = np.where((image==1) & (neighbors >= 2) & (neighbors <= 6))
  42. check_pixels = zip(fg_pixels[0], fg_pixels[1])
  43. while len(check_pixels)>0:
  44. print len(check_pixels)
  45. (image, sub1_check_pixels) = self.parallel_sub(subiterations.first_subiteration, image, check_pixels)
  46. (image, sub2_check_pixels) = self.parallel_sub(subiterations.second_subiteration, image, list(set(check_pixels+sub1_check_pixels)))
  47. check_pixels=list(set(sub1_check_pixels+sub2_check_pixels))
  48. neighbors = nd.convolve(image>0,[[1,1,1],[1,0,1],[1,1,1]],mode='constant',cval=0.0)
  49. fg_pixels = np.where(image==1)
  50. check_pixels = zip(fg_pixels[0],fg_pixels[1])
  51. (image, _) = self.parallel_sub(self.empty_pools, image, check_pixels)
  52. return image
  53. def parallel_sub(self, sub_function, image, fg_pixels):
  54. manager = Manager()
  55. queue = manager.Queue()
  56. next_queue = manager.Queue()
  57. num_procs = int(math.ceil(float(cpu_count()) * 0.75))
  58. workload_size = int(math.ceil(float(len(fg_pixels)) / float(num_procs)))
  59. process_list = []
  60. if len(fg_pixels) == 0:
  61. return (image, [])
  62. (zero_pixels, next_pixels) = sub_function(image,fg_pixels)
  63. for (x,y) in zero_pixels:
  64. image[x][y]=0;
  65. return (image, next_pixels)
  66. def PRE_first_subiteration(self, curr_image, fg_pixels):
  67. zero_pixels = { }
  68. next_pixels = { }
  69. for (i, j) in fg_pixels:
  70. if curr_image[i][j] != 1: continue
  71. p2 = curr_image[i - 1][j]
  72. p3 = curr_image[i - 1][j + 1]
  73. p4 = curr_image[i][j + 1]
  74. p5 = curr_image[i + 1][j + 1]
  75. p6 = curr_image[i + 1][j]
  76. p7 = curr_image[i + 1][j - 1]
  77. p8 = curr_image[i][j - 1]
  78. p9 = curr_image[i - 1][j - 1]
  79. if (2 <= (bool(p2) + bool(p3) + bool(p4) + bool(p5) + bool(p6) + bool(p7) + bool(p8) + bool(p9)) <= 6 and
  80. (p2 * p4 * p6 == 0) and
  81. (p4 * p6 * p8 == 0)):
  82. if ((not p2 and p3) + (not p3 and p4) + (not p4 and p5) + (not p5 and p6) + (not p6 and p7) + (not p7 and p8) + (not p8 and p9) + (not p9 and p2) == 1):
  83. zero_pixels[(i,j)] = 0
  84. if p2 == 1:
  85. next_pixels[(i-1,j)]=0
  86. if p3 == 1:
  87. next_pixels[(i-1,j+1)]=0
  88. if p4 == 1:
  89. next_pixels[(i,j+1)]=0
  90. if p5 == 1:
  91. next_pixels[(i+1,j+1)]=0
  92. if p6 == 1:
  93. next_pixels[(i+1,j)]=0
  94. if p7 == 1:
  95. next_pixels[(i+1,j-1)]=0
  96. if p8 == 1:
  97. next_pixels[(i,j-1)]=0
  98. if p9 == 1:
  99. next_pixels[(i-1,j-1)]=0
  100. return zero_pixels.keys(), next_pixels.keys()
  101. def PRE_second_subiteration(self, curr_image, fg_pixels):
  102. zero_pixels = { }
  103. next_pixels = { }
  104. for (i, j) in fg_pixels:
  105. if curr_image[i][j] != 1: continue
  106. p2 = curr_image[i - 1][j]
  107. p3 = curr_image[i - 1][j + 1]
  108. p4 = curr_image[i][j + 1]
  109. p5 = curr_image[i + 1][j + 1]
  110. p6 = curr_image[i + 1][j]
  111. p7 = curr_image[i + 1][j - 1]
  112. p8 = curr_image[i][j - 1]
  113. p9 = curr_image[i - 1][j - 1]
  114. if (2 <= (bool(p2) + bool(p3) + bool(p4) + bool(p5) + bool(p6) + bool(p7) + bool(p8) + bool(p9)) <= 6 and
  115. (p2 * p4 * p8 == 0) and
  116. (p2 * p6 * p8 == 0)):
  117. if ((not p2 and p3) + (not p3 and p4) + (not p4 and p5) + (not p5 and p6) + (not p6 and p7) + (not p7 and p8) + (not p8 and p9) + (not p9 and p2) == 1):
  118. zero_pixels[(i,j)] = 0
  119. if p2 == 1:
  120. next_pixels[(i-1,j)]=0
  121. if p3 == 1:
  122. next_pixels[(i-1,j+1)]=0
  123. if p4 == 1:
  124. next_pixels[(i,j+1)]=0
  125. if p5 == 1:
  126. next_pixels[(i+1,j+1)]=0
  127. if p6 == 1:
  128. next_pixels[(i+1,j)]=0
  129. if p7 == 1:
  130. next_pixels[(i+1,j-1)]=0
  131. if p8 == 1:
  132. next_pixels[(i,j-1)]=0
  133. if p9 == 1:
  134. next_pixels[(i-1,j-1)]=0
  135. return zero_pixels.keys(), next_pixels.keys()
  136. def empty_pools(self, curr_image, fg_pixels):
  137. zero_pixels = { }
  138. for (i, j) in fg_pixels:
  139. p2 = curr_image[i - 1][j]
  140. p3 = curr_image[i - 1][j + 1]
  141. p4 = curr_image[i][j + 1]
  142. p5 = curr_image[i + 1][j + 1]
  143. p6 = curr_image[i + 1][j]
  144. p7 = curr_image[i + 1][j - 1]
  145. p8 = curr_image[i][j - 1]
  146. p9 = curr_image[i - 1][j - 1]
  147. if (bool(p2) + bool(p3) + bool(p4) + bool(p5) + bool(p6) + bool(p7) + bool(p8) + bool(p9) > 6):
  148. zero_pixels[(i,j)] = 0
  149. return zero_pixels,[]
  150. #
  151. # helper functions
  152. #
  153. def add_zero_mat(image):
  154. num_rows, num_cols = image.shape
  155. image = np.insert(image, num_rows, np.zeros(num_cols, dtype=np.int), 0)
  156. image = np.insert(image, 0, np.zeros(num_cols, dtype=np.int), 0)
  157. num_rows, num_cols = image.shape
  158. image = np.insert(image, num_cols, np.zeros(num_rows, dtype=np.int), 1)
  159. image = np.insert(image, 0, np.zeros(num_rows, dtype=np.int), 1)
  160. return image
  161. def remove_zero_mat(image):
  162. num_rows, num_cols = image.shape
  163. image = np.delete(image, num_rows - 1, 0)
  164. image = np.delete(image, 0, 0)
  165. image = np.delete(image, num_cols - 1, 1)
  166. image = np.delete(image, 0, 1)
  167. return image
  168. def circle(radius):
  169. x, y = np.mgrid[:(2 * radius) + 1, :(2 * radius) + 1]
  170. circle = (x - radius) ** 2 + (y - radius) ** 2
  171. return (circle <= (radius ** 2)).astype(np.int)
  172. import sys, time
  173. if __name__ == '__main__':
  174. input_filename = str(sys.argv[1])
  175. output_filename = str(sys.argv[2])
  176. print "input filename: " + str(input_filename)
  177. print "output filename: " + str(output_filename)
  178. input_kde = imread(input_filename)
  179. s = GrayscaleSkeleton()
  180. start_time = time.time()
  181. skeleton = s.skeletonize(input_kde)
  182. print "total elapsed time: " + str(time.time() - start_time) + " seconds"
  183. toimage(skeleton, cmin=0, cmax=255).save(output_filename)

3.2.1 ImportError: No module named pyximport***

解决方案:
保证安装了cython,可在https://www.lfd.uci.edu/~gohlke/pythonlibs/下载对应版本,然后通过pip安装,然后,在代码中import相应包之前,添加如下代码:

  1. import pyximport; pyximport.install()
  2. import subiterations

3.2.2 Pychorm提示Unresolved reference 导入模块报错

具体情况和解决办法可参考这篇文章,亲测有效https://www.cnblogs.com/NancyRM/p/8258372.html

3.2.3 ImportError: Building module subiterations failed: [‘DistutilsPlatformError: Unable to find vcvarsall.bat\n’](生成模块子迭代失败

在这里插入图片描述(1)关于 ‘DistutilsPlatformError: Unable to find vcvarsall.bat\n’的解决可见
Unable to find vcvarsall.bat 里面整理的非常全面,找到python2.7的路径:D:\Python27\Lib\distutils

找到:msvc9compiler.py修改两个地方:具体的路径以自己安装路径为准
如下:

  1. def get_build_version():
  2. """Return the version of MSVC that was used to build Python. For Python 2.3 and up, the version number is included in sys.version. For earlier versions, assume the compiler is MSVC 6. """
  3. return 9.0
  4. prefix = "MSC v."
  5. i = sys.version.find(prefix)
  6. if i == -1:
  7. return 6
  8. i = i + len(prefix)
  9. s, rest = sys.version[i:].split(" ", 1)
  10. majorVersion = int(s[:-2]) - 6
  11. minorVersion = int(s[2:3]) / 10.0
  12. # I don't think paths are affected by minor version in version 6
  13. if majorVersion == 6:
  14. minorVersion = 0
  15. if majorVersion >= 6:
  16. return majorVersion + minorVersion
  17. # else we don't know what version of the compiler this is
  18. return None
  19. def find_vcvarsall(version):
  20. """Find the vcvarsall.bat file At first it tries to find the productdir of VS 2008 in the registry. If that fails it falls back to the VS90COMNTOOLS env var. """
  21. return r'C:\Users\87792\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\vcvarsall.bat'
  22. vsbase = VS_BASE % version
  23. try:
  24. productdir = Reg.get_value(r"%s\Setup\VC" % vsbase,
  25. "productdir")
  26. except KeyError:
  27. productdir = None

3.2.4 ImportError: Building module subiterations failed: [“CompileError: command ‘C:\\Users\\87792\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\amd64\\cl.exe’ failed with exit status 2\n”]

暂时还未找到解决办法

发表评论

表情:
评论列表 (有 0 条评论,94人围观)

还没有评论,来说两句吧...

相关阅读