如何使用OpenCV实现图像矢量化(元素分割)提取独立对象
图像元素拆分需求说明
我使用“vectorize(矢量化)”这一术语是因为它一直被用来描述我正在说明的处理流程,我不清楚它的官方命名,我想要实现的是将图像中的元素拆分,分别保存为独立图像。
以下是我想要进行“矢量化”处理的示例图片:
我希望通过OpenCV实现的功能为:将玉米穗与其连接的绿色秸秆分离,同时将玉米穗上的每块玉米粒都拆分出来,保存为单独的图像。
以下是我已经尝试编写的实现代码:
def kmeansSegmentation(path_to_images, image_name, path_to_save_segments): img = cv2.imread(path_to_images+image_name) img_blur = cv2.GaussianBlur(img, (3,3), 0) img_gray = cv2.cvtColor(img_blur, cv2.COLOR_BGR2GRAY) img_reshaped = img_gray.reshape((-1, 3)) img_reshaped = np.float32(img_reshaped) criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0) K = 5 attempts = 10 ret,label,center=cv2.kmeans(img_reshaped,K,None,criteria,attempts,cv2.KMEANS_PP_CENTERS) center = np.uint8(center) res = center[label.flatten()] v = np.median(res) sigma=0.33 lower = int(max(0, (1.0 - sigma) * v)) upper = int(min(255, (1.0 + sigma) * v)) edges = cv2.Canny(img_gray, lower, upper) contours, hierarchy = cv2.findContours(edges.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) sorted_contours= sorted(contours, key=cv2.contourArea, reverse= True) mask = np.zeros(img.shape[:2], dtype=img.dtype) array_of_contour_areas = [cv2.contourArea(contour) for contour in contours] contour_avg = sum(array_of_contour_areas)/len(array_of_contour_areas) contour_var = sum(pow(x-contour_avg,2) for x in array_of_contour_areas) / len(array_of_contour_areas) contour_std = math.sqrt(contour_var) print("Saving segments", len(sorted_contours)) for (i,c) in tqdm(enumerate(sorted_contours)): if (cv2.contourArea(c) > contour_avg-contour_std*2): x,y,w,h= cv2.boundingRect(c) cropped_contour= img[y:y+h, x:x+w] cv2.drawContours(mask, [c], 0, (255), -1) result = cv2.bitwise_and(img, img, mask=mask) return result
注:代码中原注释内容为调试过程中用于观察图像变化的测试代码,可直接忽略。
内容的提问来源于stack exchange,提问作者sololuvr
相关产品推荐
相关产品推荐

