dxf_to_png.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import dxfgrabber
  2. import cv2
  3. import numpy as np
  4. import sys
  5. #https://gist.github.com/msjamali52/91a96176a1be3313af5d3309cbbf4b06
  6. """
  7. def absdiff(num1, num2):
  8. if num1 <= num2:
  9. return num2 - num1
  10. else:
  11. return num1 - num2
  12. """
  13. def getMinXY(shapes):
  14. minX, minY = 99999, 99999
  15. for shape in shapes:
  16. if shape.dxftype == 'LINE':
  17. minX = min(minX, shape.start[0], shape.end[0])
  18. minY = min(minY, shape.start[1], shape.end[1])
  19. elif shape.dxftype == 'ARC':
  20. minX = min(minX, shape.center[0])
  21. minY = min(minY, shape.center[1])
  22. return minX, minY
  23. def getMaxXY(shapes):
  24. maxX, maxY = -99999, -99999
  25. for shape in shapes:
  26. if shape.dxftype == 'LINE':
  27. maxX = max(maxX, shape.start[0], shape.end[0])
  28. maxY = max(maxY, shape.start[1], shape.end[1])
  29. elif shape.dxftype == 'ARC':
  30. maxX = max(maxX, shape.center[0])
  31. maxY = max(maxY, shape.center[1])
  32. return maxX, maxY
  33. #Translate x,y values as per fourth quadrant i.e positive x and negative y. Update y value to positive, to be used by opencv axes.
  34. # shift origin of image by 100 pixels for better clarity of output image
  35. def getXY(point):
  36. x, y = point[0], point[1]
  37. return int(x-minX+100), int(abs(y-maxY)+100)
  38. dxf = dxfgrabber.readfile("GV_12.DXF")
  39. shapes = dxf.entities.get_entities()
  40. minX, minY = getMinXY(shapes)
  41. maxX, maxY = getMaxXY(shapes)
  42. #baseX, baseY = absdiff(minX, 0), absdiff(minY, 0)
  43. #absMaxX, absMaxY = absdiff(maxX, 0), absdiff(maxY, 0)
  44. print(maxX, maxY)
  45. print(minX, minY)
  46. #print(absMaxX, absMaxY)
  47. #print(baseX, baseY)
  48. canvas = np.zeros((512,512,3), np.uint8)
  49. for shape in shapes:
  50. if shape.dxftype == 'LINE':
  51. x1, y1 = getXY(shape.start)
  52. x2, y2 = getXY(shape.end)
  53. canvas = cv2.line(canvas, (x1,y1), (x2,y2), (255, 0, 255), 1)
  54. elif shape.dxftype == 'ARC':
  55. centerX, centerY = getXY(shape.center)
  56. if (shape.start_angle > 180) and (shape.end_angle < shape.start_angle):
  57. canvas = cv2.ellipse(canvas, (centerX, centerY), (int(shape.radius), int(shape.radius)), 180, int(shape.start_angle) - 180, 180 + int(shape.end_angle), (0, 0, 255), 1)
  58. else:
  59. canvas = cv2.ellipse(canvas, (centerX, centerY), (int(shape.radius), int(shape.radius)), 0, int(360 - shape.start_angle), int(360 - shape.end_angle), (0, 0, 255), 1)
  60. cv2.imshow('test', canvas)
  61. cv2.waitKey(50)
  62. # To save canvas use cv2.imwrite()
  63. #cv2.imwrite('res.png', canvas)
  64. cv2.waitKey(0)
  65. cv2.destroyAllWindows()