I have a picture which has multiple mechanical components. They were exported directly from the dxf file using ezdxf. How can I divide them draw each one to an image separately? I have tried using contours, hierarchy = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
to draw them by plt
by points in contours
. However, the graph will be blurred. Is there any methods that can help me out?
Below is the picture. Thanks in advance
picture
I am considering that the input image is stored in the variable "inImage". This image is a binary image with only 0/255 values for each pixel. Use the code below to get each of the mechanical components on separate images.
# Finding the contours
Contours = cv2.findContours(inImage, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[-2]
ComponentImages = []
for Contour in Contours:
# Getting the bounding box of the contour
x, y, w, h = cv2.boundingRect(Contour)
# Extracting the mechanical component from the original image
img = inImage[y:y+h, x:x+w].copy()
# Creating the mask image of the contour separately
maskImg = np.zeros((h, w), dtype=np.uint8)
cv2.drawContours(maskImg, [Contour], -1, 255, -1)
# Performing bitwise operation to remove any part if not inside this contour
img = cv2.bitwise_and(img, maskImg)
# Storing this component image
ComponentImages.append(img)
Finally, "ComponentImages" will store the images of each mechanical component.