灰度图
边缘检测后进行连通性分析的结果
填充
最终结果
import numpy as np
import cv2imgfile = r"F:cartography 524datadataFromLvAmericaca_kr_300.png"
#函数中的第二个形参是一个数值,面积小于该数值的斑块会被删除
def remove_small_area(imgfile,area_name):#读取图像img = cv2.imread(imgfile)img = dianBlur(img, 5)#将图像转为灰度图像img_gray= cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)#sobel算子监测边缘x_gray = cv2.Sobel(img_gray, cv2.CV_32F, 1, 0)y_gray = cv2.Sobel(img_gray, cv2.CV_32F, 0, 1)x_gray = vertScaleAbs(x_gray)y_gray = vertScaleAbs(y_gray)dst = cv2.add(x_gray, y_gray, dtype=cv2.CV_16S)dst = vertScaleAbs(dst)#连通区域分析num_labels, labels, stats, centers = tedComponentsWithStats(dst, connectivity=8, ltype=cv2.CV_32S)# 参数说明:# num_labels: 代表连通域的数量,包含背景# labels : 记录img中每个位置对应的label# stats: 每个连通域的外接矩形和面积# x, y, w, h, area = stats[t]# centers : 连通域的质心坐标for t in range(1, num_labels, 1):x, y, w, h, area = stats[t]if area > area_name:index = np.where(labels == t)labels[index[0], index[1]] = 0# 把斑点位置保存在mask中,The mask must be 8-bit 1-channel image in function 'icvInpaint'mask = np.array(labels, np.uint8)#将mask二值化,由于现在的mask只有轮廓,所以要将轮廓内部填充ret, thresh = cv2.threshold(mask, 0, 255, cv2.THRESH_BINARY)#找到最外层轮廓,该方法的第二个参数就是找最外层轮廓contours, hierachy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, 1)#填充result = cv2.fillPoly(thresh, contours, (255, 255, 255))#修复图像,mask地方的像素值由周围的像素值决定dst_TELEA = cv2.inpaint(img, result, 3, cv2.INPAINT_TELEA)#绘制最终结果cv2.imshow('result', dst_TELEA)cv2.waitKey(0)remove_small_area(imgfile,300)
参考大佬的博客:
=aHR0cHM6Ly9jbi5iaW5nLmNvbS8%3D
本文发布于:2024-02-04 22:13:49,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170717595760073.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |