I’m trying to use OpenCV for the first time to try and find the contours of several regions in a labelmap. Every region has its own numeric integer value. However it seems the contours are drawn from the pixel-centers instead of around the pixels. Is there a way to get it to draw contours around the pixels?
Here the same problem is encountered three years ago.
Here is some demo-code and an image to show what I mean:
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
lblmap = np.array([[0, 1, 1, 0, 0],
[0, 1, 1, 2, 0],
[0, 0, 1, 0, 2],
[3, 3, 3, 2, 2],
[0, 3, 0, 2, 0]])
ax.imshow(lblmap)
mask = np.zeros(lblmap.shape, dtype=np.uint8)
nROI = np.max(lblmap)
areas = []
for roi_id in range(1, 1 + nROI):
cv.compare(lblmap, int(roi_id), cv.CMP_EQ, mask)
contour, _ = cv.findContours(mask, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
x = np.hstack((contour[0][:, 0, 0], contour[0][:, 0, 0][0]))
y = np.hstack((contour[0][:, 0, 1], contour[0][:, 0, 1][0]))
areas.append({'shape': (x, y), 'color': (1, 0, 0)})
fig, ax = plt.subplots(figsize=(45, 30))
for area in areas:
ax.plot(area['shape'][0], area['shape'][1], color=area['color'])