我正在考虑输入图像存储在变量“inImage”中。此图像是一个二值图像,每个像素只有 0/255 个值。使用下面的代码在单独的图像上获取每个机械组件。
# 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)
最后,“ComponentImages”将存储每个机械部件的图像。