我正在编写一个Python脚本,用于将图像转换为CNC机器的G代码。 CNC机器使用直径为0.250英寸的圆柱头。我的脚本在图像中找到轮廓,然后将轮廓中的坐标转换为机器的方向。
这很好,除了雕刻的形状比设计的零件小0.125英寸。钻头的中心直接在轮廓上移动,因此产生的形状太小,只有钻头直径的一半。
我想将每个轮廓扩大x
像素。我要制作一个输出图像,其中源图像中每个白色的像素在输出图像中也是白色,而且每个像素在输入图像中白色像素的x像素之内应该在输出图像中为白色。这是我的源图像:
使用cv2.dilate()
扩展轮廓不会产生我想要的结果,因为它倾向于使圆形边缘变成正方形。
img = cv2.dilate(img, 15, 5)
我尝试逐个像素地遍历图像,然后使用cv2.pointPolygontest(contour, (x,y), True)
测试到轮廓的距离。可以,但是这种破解非常慢。
import cv2 import numpy as np def erode_contours_by_cutter_size(img, contours, cutter_size): # Create an output image outputImage = np.zeros_like(img) # Iterate through every pixel in the image for x in range(img.shape[0]): for y in range(img.shape[1]): # Check if the pixel is black if img[y,x] != 255: # Check if the distance from this pixel to a contour is smaller than the cutter size for contour in contours: dist = cv2.pointPolygonTest(contour, (x,y), True) if abs(dist) < cutter_size: outputImage[y,x] = 255 return outputImage img = 255-cv2.imread('/home/stephen/Desktop/t2.png',0) img = cv2.resize(img, (234,234)) cutter_size = 50 contours, _ = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) img = erode_contours_by_cutter_size(img, contours, cutter_size) cv2.imshow('img', img) cv2.waitKey(0) cv2.destroyAllWindows()
这是outputImage:
我正在编写一个Python脚本,用于将图像转换为CNC机器的G代码。 CNC机器使用直径为0.250英寸的圆柱头。我的脚本在...
这可能不是最干净的解决方案,但是它很容易,并且可以用于所有形状。通过一些额外的工作,您也可以将其用于模板中的切口。因此,满足您的需求可能就足够了。