Here is a solution to compare two CAD graphs using Python and mark the differences, combining image processing and CAD structure analysis:
1. Environment preparation and library selection
Image processing library: Use OpenCV for image difference detection, color space conversion and contour analysis.
CAD parsing library: If it is in DXF format, use ezdxf to parse entity information (such as blocks, lines, circles, etc.).
Geometric Computing Library: scikit-image is used for structural similarity (SSIM) and affine transformation matching.
import cv2 import ezdxf from import structural_similarity
2. Key steps to achieve
1. Loading and preprocessing
Image format: Use OpenCV to read the picture and convert it to grayscale for Gaussian blur denoising.
left_img = ("") right_img = ("") gray_left = (left_img, cv2.COLOR_BGR2GRAY) gray_right = (right_img, cv2.COLOR_BGR2GRAY)
DXF format: Extract entity coordinates and attributes through ezdxf.
doc_left = ("") doc_right = ("")
2. Red frame area detection
Color threshold method: identify the red area in the HSV space and extract the coordinates of the red frame.
hsv = (right_img, cv2.COLOR_BGR2HSV) lower_red = ([0, 50, 50]) upper_red = ([10, 255, 255]) mask = (hsv, lower_red, upper_red) contours, _ = (mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
3. Difference detection
Image difference method: Added parts by pixel comparison.
diff = (gray_left, gray_right) _, thresh = (diff, 30, 255, cv2.THRESH_BINARY)
Entity comparison method (DXF): traverse the entity in the right image and check whether it exists in the left image.
right_entities = { for entity in doc_right.modelspace()} left_entities = { for entity in doc_left.modelspace()} new_entities = right_entities - left_entities
4. Rotation matching detection
Affine transformation matching: Rotate the parts in the left image and calculate the similarity to the red frame area in the right image.
(height, width) = right_roi.shape[:2] center = (width // 2, height // 2) rotation_matrix = cv2.getRotationMatrix2D(center, angle=90, scale=1) rotated_left = (left_roi, rotation_matrix, (width, height)) ssim_score = structural_similarity(rotated_left, right_roi) if ssim_score > 0.8: # Threshold value can be adjusted (right_img, (x, y), (x+w, y+h), (0, 255, 0), 2) # Parts marked as rotated
5. Result Marking
In the picture right, mark the rotated parts with a green box and mark the completely added parts with a red box.
for (x, y, w, h) in new_contours: (right_img, (x, y), (x+w, y+h), (0, 0, 255), 2)
3. Optimization and precautions
Threshold adjustment: Adjust the SSIM similarity threshold (such as 0.7-0.9) according to the actual image quality.
Multi-angle rotation matching: If the rotation angle is unknown, you can traverse 0°-360° to find the maximum matching value.
Vector data priority: If it is a DXF file, it is more efficient to directly compare entity attributes.
Sample output effect
Red box: New independent parts added in the picture on the right.
Green box: The part in the left image exists in the area in the right image after being rotated.
By combining image differences and geometric transformation matching, new and transformed parts can be accurately identified. If complete code or parameter tuning details are required, the CAD sample file can be further provided.
4. Supplementary method
1. Find and mark the difference between two pictures based on openCV and python skimage
Code implementation
Import image processing library
from import structural_similarity as compare_ssim import imutils import cv2 import numpy as np
Read pictures
image = "C:/Users/ts/Desktop/img/" imageCompare = "C:/Users/ts/Desktop/img/" image= ((image, dtype=np.uint8), -1) image_compare= ((image_compare, dtype=np.uint8), -1)
Adjust the size of the two pictures in comparison
h1, w1,c1 = h2, w2,c2= image_compare = (image_compare ,dsize=(w1,h1))
Picture to grayscale
gray_image= (image,cv2.COLOR_BGR2GRAY) gray_image_ompare = (image_compare ,cv2.COLOR_BGR2GRAY)
Use structural_similarity comparison to get image similarity and difference
(score,diff) = compare_ssim(gray_image,gray_image_ompare ,full = True) diff = (diff *255).astype("uint8") retval,thresh = (diff,200,255,cv2.THRESH_BINARY_INV) # Parameter thresh: Thresh, used to determine whether the pixel should be regarded as foreground or background. It is more appropriate to adjust the measurement of 200.cnts=((),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[1] if imutils.is_cv3() else cnts[0] loacation_list =[] for c in cnts: (x,y,w,h) = (c) loacation_list.append((x,y,x+w,y+h))
Circle the different and mark the serial number
for index,item in enumerate(loacation_list): #Circle the difference x,y,x1,y1 = item (imageA,(x,y),(x1,y1),(0,0,255),2) (imageB,(x,y),(x1,y1),(0,0,255),2) #Add serial numbers in different places imageA = (imageA,str(index+1), (x,y+24), cv2.FONT_HERSHEY_DUPLEX, 1, (0, 0, 255))
2. Use OpenCV to compare the similarity of two pictures
Implement code
import ; import ; import ; import ; import ; import ; import ; public class ImageSimilarity { static { // Set the library path ("", "D:\\anzhuang\\opencv\\opencv\\build\\java\\x64"); // Load the OpenCV library (Core.NATIVE_LIBRARY_NAME); } /** * Compare the similarity between the two pictures * @param imgPath1 The path to picture 1 * @param imgPath2 Path to picture 2 * @return Similarity value (range: 0 to 1, 1 means exactly the same) */ public static double compareImages(String imgPath1, String imgPath2) { // Load the picture Mat img1 = (imgPath1); Mat img2 = (imgPath2); // Convert to grayscale Mat grayImg1 = new Mat(); Mat grayImg2 = new Mat(); (img1, grayImg1, Imgproc.COLOR_BGR2GRAY); (img2, grayImg2, Imgproc.COLOR_BGR2GRAY); // Calculate histogram Mat hist1 = new Mat(); Mat hist2 = new Mat(); MatOfInt histSize = new MatOfInt(256); // Histogram size MatOfFloat ranges = new MatOfFloat(0f, 256f); // Pixel value range ((grayImg1), new MatOfInt(0), new Mat(), hist1, histSize, ranges); ((grayImg2), new MatOfInt(0), new Mat(), hist2, histSize, ranges); // Compare histogram return (hist1, hist2, Imgproc.CV_COMP_CORREL); } public static void main(String[] args) { String imgPath1 = "path/to/"; String imgPath2 = "path/to/"; double similarity = compareImages(imgPath1, imgPath2); ("Image Similarity: " + similarity); } }
This is the article about Python comparing two pictures and marking the differences. For more related Python picture comparison content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!