top of page
DALL·E 2025-01-22 23.11.10 - A vertical, futuristic design for a website background that c
Search

Image Processing with Python and AutoCAD Integration: Detecting Lines and Exporting to DWG File

In today’s world, image processing and converting visual data into digital drawings has become a significant field. Python, with its powerful libraries, is an extremely useful tool for this process. Particularly, image processing with OpenCV (cv2) and drawing creation with AutoCAD are widely used in many industries and engineering fields. Python offers an excellent platform by combining these two powerful tools, enabling the detection, analysis, and transfer of visual data to AutoCAD. In this project, I aimed to detect lines from an image and transfer this data to AutoCAD to create a drawing.

You can find my other projects related to AutoCAD and Python integration at the following GitHub link.


This code reads an image, performs edge detection, and linear line detection. Then, the detected lines are transferred to AutoCAD and saved as a DWG file. The key steps of the code are as follows:

  1. Image Reading and Verification: The image is checked to ensure it is loaded properly.

  2. Grayscale Conversion: The image is converted to grayscale for edge detection.

  3. Edge Detection: Edges in the image are detected using the Canny algorithm.

  4. Line Detection: Lines along the edges are detected using the Hough Transform algorithm.

  5. Transfer to AutoCAD: The detected lines are scaled and drawn in AutoCAD, and a DWG file is generated.



1. Installing the Required Libraries

To run our project, you can install the necessary libraries via the terminal with the following commands:

pip install opencv-python # OpenCV 
pip install numpy # NumPy 
pip install pyautocad # PyAutoCAD 
pip install matplotlib # Matplotlib

First, we start by importing the necessary libraries. These libraries are used for image processing and AutoCAD integration.

# We import the necessary libraries.
import cv2
import numpy as np
import matplotlib.pyplot as plt
from pyautocad import Autocad, APoint
  • cv2: The OpenCV library is used for image processing.

  • numpy: Used for numerical operations.

  • matplotlib.pyplot: Used for displaying images.

  • pyautocad: Used for interacting with AutoCAD.


  1. Reading and Verifying the Image

The image I will process is shown below:

1. Photo Used
1. Photo Used

We load the image file and check if it has been loaded correctly.

# Specify the path of the image to be processed
image_path = 'image2.png'

# Check if the image has been loaded correctly
img = cv2.imread(image_path)

if img is None:
    # Print an error message if the image cannot be loaded
    print(f"Error: The image at {image_path} could not be loaded.")
else:
    # Print the dimensions of the image if it is successfully loaded
    print(f"Image loaded successfully. Shape: {img.shape}")
  • cv2.imread(): Loads the image from the specified path.

  • If it cannot be loaded, an error message is displayed; otherwise, if the image is successfully loaded, the dimensions are printed.


3. Convert the Image to Grayscale

We convert the image to grayscale to make it suitable for edge detection.

# We convert the image to grayscale format
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  • cv2.cvtColor(): Converts the image from color (BGR) format to grayscale.


4. Edge Detection

We use the Canny edge detection algorithm to detect edges in the image.

# We use the Canny algorithm for edge detection.
edges = cv2.Canny(gray, 30, 200, apertureSize=7)
  • cv2.Canny(): Detects edges using the Canny algorithm. Here, 30 and 200 are the low and high threshold values, and you can adjust these values to change the sensitivity.


5. Line Detection with Hough Transform

We use the Hough Transform algorithm to detect lines along the edges.

# We detect lines passing through the edges using the Hough Transform.
lines = cv2.HoughLinesP(edges, 1, np.pi / 180, threshold=50, minLineLength=2, maxLineGap=50)
  • cv2.HoughLinesP(): The Hough linear transform algorithm detects lines on the edges. The threshold parameter specifies the minimum number of pixels required for line detection.


6. Visualizing the Detected Lines

We visualize the detected edges and lines. First, we display the edges in a window.

# We open the image showing the edges on the screen.
cv2.imshow("Detected Edges", edges)
cv2.waitKey(0)  # Wait until the user presses a key.
cv2.destroyAllWindows()
  • cv2.imshow(): Displays the image in a window.

    cv2.waitKey(): Waits for the user to press a key.

    cv2.destroyAllWindows(): Closes the image window.

    2. Detected Edges
    2. Detected Edges

Later, we draw the detected lines on the original image.

# Drawing the detected lines on the original image (for visualization)
for line in lines:
    x1, y1, x2, y2 = line[0]
    cv2.line(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
  • cv2.line(): Draws the detected lines on the original image.

Finally, we display the image with the drawn lines.

#  Displaying the image with the drawn lines on the screen
cv2.imshow("Detected Lines", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
3. Detected Lines
3. Detected Lines
  1. AutoCAD Integration and Saving as DWG File

We transfer the detected lines to AutoCAD and create a DWG file.

First, we start a session for AutoCAD:

# Starting an AutoCAD session
acad = Autocad(create_if_not_exists=True)
acad.app.Documents.Add()  # Creating a new AutoCAD document
  • Autocad(): Creates an object to interact with AutoCAD.

  • acad.app.Documents.Add(): Creates a new AutoCAD document.

Now, we draw the detected lines in the AutoCAD environment:

# We are drawing the detected lines in the AutoCAD environment.
for line in lines:
    x1, y1, x2, y2 = line[0]
    # We are converting the pixel coordinates to AutoCAD coordinates using a scaling factor.
    start_point = APoint(x1 * scaling_factor, y1 * scaling_factor)
    end_point = APoint(x2 * scaling_factor, y2 * scaling_factor)
    acad.model.AddLine(start_point, end_point)
  • APoint(): Creates a point with coordinates converted to AutoCAD's coordinate system.

  • acad.model.AddLine(): Adds a line to the AutoCAD model.

Finally, we save the DWG file:

# We save the AutoCAD drawing as a DWG file.
acad.app.ActiveDocument.SaveAs("/Documents/autocad/drawing18.dwg")
print("DWG file saved as 'generated_floor_plan.dwg'")

SaveAs(): Saves the AutoCAD drawing in DWG format at the specified file path.

4. Drawing in DWG File
4. Drawing in DWG File
  1. (Optional) Closing the AutoCAD Document

You can close the AutoCAD document if you wish, but this step is optional.

# Optional: Closing the AutoCAD document (You can remove this section if you want it to remain open)
# acad.app.ActiveDocument.Close()

With these explanations, I aimed to help you better understand the operation of the code by breaking down each step in detail. The code detects edges in the image, identifies the lines, then transfers them to the AutoCAD environment and finally saves them in DWG format for export. This process successfully integrates image processing and AutoCAD, making it possible to convert visual data into digital drawings.

 
 
 

Comments


bottom of page