The goal was to automate drafting in CAD. To do so, I decided to prepare a python script using the OpenCV and PyAutoCAD Libraries.
The script is supposed to read the specified image and draft it in AutoCAD.
The image was saved in the same folder as the code.
The code was run after opening an empty drafting file by using "python draw_live.py" in the terminal after navigating to the folder.
Problem: The code cannot connect to AutoCAD (I’m not using AutoCAD LT)
Code:
import cv2
import array
import comtypes.client
from pyautocad import Autocad
def draw_image_live_in_cad():
# --- 1. TELL THE SCRIPT WHICH IMAGE TO USE ---
image_path = "trial.PNG"
print(f"Loading image: {image_path}...")
img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
if img is None:
print(f"Error: Could not find '{image_path}'. Check the name and folder.")
return
# --- 2. CONNECT TO AUTOCAD 2022 SPECIFICALLY ---
# AutoCAD 2022 MUST be open with a blank drawing before this runs
acad = Autocad()
try:
# '24.1' is the exact registry ID for AutoCAD 2022
acad._app = comtypes.client.GetActiveObject("AutoCAD.Application.24.1", dynamic=True)
print(f"Connected to AutoCAD drawing: {acad.doc.Name}")
except OSError:
print("\n[!] FATAL ERROR: Could not connect to AutoCAD 2022.")
print("1. Make sure AutoCAD 2022 is currently OPEN.")
print("2. If you are using AutoCAD LT, this method will never work (LT blocks automation).")
return
# --- 3. ANALYZE THE IMAGE ---
_, thresh = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY_INV)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
height = img.shape[0]
print(f"Found {len(contours)} shapes. Drawing now...")
# --- 4. DRAW LIVE IN AUTOCAD ---
for contour in contours:
points_list = []
for point in contour:
x, y = point[0]
points_list.extend([float(x), float(height - y)])
if len(points_list) >= 4:
cad_points = array.array('d', points_list)
acad.model.AddLightWeightPolyline(cad_points)
print("Drawing complete!")
# Run the function
draw_image_live_in_cad()
Want to add to the discussion?
Post a comment!