在 OpenCV 中基于线分割图像和标签分割
Split image and tag splits based on line in OpenCV
我有一张图片可以用轮廓线分割。我想拆分它并在其质心上标记每一块。我很清楚如何在其质心上标记轮廓,但不知道如何获得该轮廓。
import cv2
img = cv2.imread(path)
contours = get_contours() # this I don't know how to do
def get_centroid(c):
positions = []
M = cv2.moments(c)
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
return (cx,cy)
centroids = [get_centroid(c) for c in contours]
for ix, centroid in enumerate(centroids):
cv2.putText(
img,
text=str(ix),
org=centroid,
fontFace=cv2.FONT_HERSHEY_SIMPLEX,
fontScale=1,
color=(0, 0, 0),
thickness=1,
lineType=cv2.LINE_AA,
)
您可以为此使用 cv2.findContours
。
这是一个示例方法
image = cv2.imread(path)
### converting to gray scale
gray_scale=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
### applying blur layer to connect nearby pixels
blur = cv2.GaussianBlur(gray_scale,(5,5),0)
### binarising
th1,img_bin=cv2.threshold(blur,150,225,cv2.THRESH_OTSU)
### finding contours
contours, hierarchy = cv2.findContours(img_bin, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
### draw all contours
image = cv2.drawContours(image, contours, -1, (0, 255, 0), 2)
def get_centroid(c):
positions = []
M = cv2.moments(c)
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
return (cx,cy)
centroids = [get_centroid(c) for c in contours]
for x,y in centroids:
image = cv2.circle(image, (x,y), radius=3, color=(0, 0, 255), thickness=-1)
这是我们得到的输出。绿色表示检测到的轮廓,蓝点是质心。
我有一张图片可以用轮廓线分割。我想拆分它并在其质心上标记每一块。我很清楚如何在其质心上标记轮廓,但不知道如何获得该轮廓。
import cv2
img = cv2.imread(path)
contours = get_contours() # this I don't know how to do
def get_centroid(c):
positions = []
M = cv2.moments(c)
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
return (cx,cy)
centroids = [get_centroid(c) for c in contours]
for ix, centroid in enumerate(centroids):
cv2.putText(
img,
text=str(ix),
org=centroid,
fontFace=cv2.FONT_HERSHEY_SIMPLEX,
fontScale=1,
color=(0, 0, 0),
thickness=1,
lineType=cv2.LINE_AA,
)
您可以为此使用 cv2.findContours
。
这是一个示例方法
image = cv2.imread(path)
### converting to gray scale
gray_scale=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
### applying blur layer to connect nearby pixels
blur = cv2.GaussianBlur(gray_scale,(5,5),0)
### binarising
th1,img_bin=cv2.threshold(blur,150,225,cv2.THRESH_OTSU)
### finding contours
contours, hierarchy = cv2.findContours(img_bin, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
### draw all contours
image = cv2.drawContours(image, contours, -1, (0, 255, 0), 2)
def get_centroid(c):
positions = []
M = cv2.moments(c)
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
return (cx,cy)
centroids = [get_centroid(c) for c in contours]
for x,y in centroids:
image = cv2.circle(image, (x,y), radius=3, color=(0, 0, 255), thickness=-1)