## Python 3 dxfgrabber Script to Convert AutoCAD Drawings DWG/DFG Figures to PNG or JPEG Image File Full Project For Beginners Welcome folks today in this blog post we will be converting `autocad drawings` to image files using `dxfgrabber` library in python. All the full source code of application is given below.

# Get Started

In order to get started you need to install the following libraries using the `pip` command as shown below

`pip install dxfgrabber`

After installing this library make an `app.py` file and copy paste the following code

`app.py`

``````import dxfgrabber
import cv2
import numpy as np
import sys

"""
def absdiff(num1, num2):
if num1 <= num2:
return num2 - num1
else:
return num1 - num2
"""

def getMinXY(shapes):
minX, minY = 99999, 99999
for shape in shapes:
if shape.dxftype == 'LINE':
minX = min(minX, shape.start, shape.end)
minY = min(minY, shape.start, shape.end)
elif shape.dxftype == 'ARC':
minX = min(minX, shape.center)
minY = min(minY, shape.center)

return minX, minY

def getMaxXY(shapes):
maxX, maxY = -99999, -99999
for shape in shapes:
if shape.dxftype == 'LINE':
maxX = max(maxX, shape.start, shape.end)
maxY = max(maxY, shape.start, shape.end)
elif shape.dxftype == 'ARC':
maxX = max(maxX, shape.center)
maxY = max(maxY, shape.center)

return maxX, maxY

#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.
# shift origin of image by 100 pixels for better clarity of output image
def getXY(point):
x, y = point, point
return int(x-minX+100), int(abs(y-maxY)+100)

shapes = dxf.entities.get_entities()
minX, minY = getMinXY(shapes)
maxX, maxY = getMaxXY(shapes)
#baseX, baseY = absdiff(minX, 0), absdiff(minY, 0)
#absMaxX, absMaxY = absdiff(maxX, 0), absdiff(maxY, 0)

print(maxX, maxY)
print(minX, minY)
#print(absMaxX, absMaxY)
#print(baseX, baseY)

canvas = np.zeros((512,512,3), np.uint8)
for shape in shapes:
if shape.dxftype == 'LINE':
x1, y1 = getXY(shape.start)
x2, y2 = getXY(shape.end)
canvas = cv2.line(canvas, (x1,y1), (x2,y2), (255, 0, 255), 1)
elif shape.dxftype == 'ARC':
centerX, centerY = getXY(shape.center)
if (shape.start_angle > 180) and (shape.end_angle < shape.start_angle):
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)
else:
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)
cv2.imshow('test', canvas)
cv2.waitKey(50)

cv2.imwrite('res.png', canvas)
cv2.waitKey(0)
cv2.destroyAllWindows()``````

See also  Python 3 PyQt5 Company Employee Management System Using SQLite Database GUI Desktop App Full Project For Beginners

Now if you run this python script `app.py` by typing the below command

`python app.py input.dwg`

Here we are providing the `input` file as a command line argument to the script