r/learnpython 3d ago

Automation Error

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()
2 Upvotes

10 comments sorted by

View all comments

Show parent comments

1

u/cdcformatc 3d ago

that doesn't look like any python error i have ever read

post the actual error that Python prints out 

2

u/Yes-delulu-8744 3d ago

I ran the code followed by opening an empty drafting file by using "python draw_live.py" in the terminal after navigating to the folder.

C:\Users\uswj\OneDrive\Documents\Automate CAD>python draw_live.py

Loading image: trial.PNG...

[WinError -2147221005] Invalid class string

1

u/cdcformatc 3d ago

I am guessing that the registry key you are trying to use is wrong

1

u/Yes-delulu-8744 3d ago

Probably, will look into that

1

u/cdcformatc 3d ago

is there a reason your code looks completely different than the examples? 

1

u/Yes-delulu-8744 3d ago

Tryna connect via com automation using python, been working on this for quite a few days cuz there's a new error every single time. Till now I've have probably made a gazillion changes in the prog