我是 OpenCV 的新手,我什至不确定如何解决这个问题。我有这张 500x500 像素的图片,里面有红点和白线。
以每个红点为中心,我可以在红点周围绘制一个 25X25 大小的固定边界框吗?我需要识别图像中的每个红点。
注意:条件是我需要找到一个固定大小(25x25)的边界框,红点必须在边界框的中心。
如有任何帮助,我们将不胜感激。提前谢谢你。
最佳答案
另一种解决方案,使用 numpy
slicing获得红色 channel ,where
创建红点和cv2.findContours
的掩码获取点的边界矩形。我们可以使用此信息绘制新的 25 x 25
矩形:
# Imports
import cv2
import numpy as np
# Read image
imagePath = "C://opencvImages//"
inputImage = cv2.imread(imagePath + "oHk9s.png")
# Deep copy for results:
inputImageCopy = inputImage.copy()
# Slice the Red channel from the image:
r = inputImage[:, :, 2]
# Convert type to unsigned integer (8 bit):
r = np.where(r == 237, 255, 0).astype("uint8")
# Extract blobs (the red dots are all the white pixels in this mask):
contours, _ = cv2.findContours(r, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
# Store bounding rectangles here:
boundingRectangles = []
# Loop through the blobs and draw a 25 x 25 green rectangle around them:
for c in contours:
# Get dot bounding box:
x, y, w, h = cv2.boundingRect(c)
# Set new bounding box dimensions:
boxWidth = 25
boxHeight = 25
# Center rectangle around blob:
boxX = int(x + 0.5 * (w - boxWidth))
boxY = int(y + 0.5 * (h - boxHeight))
# Store data:
boundingRectangles.append((boxX, boxY, boxWidth, boxHeight))
# Draw and show new bounding rectangles
color = (0, 255, 0)
cv2.rectangle(inputImageCopy, (boxX, boxY), (boxX + boxWidth, boxY + boxHeight), color, 2)
cv2.imshow("Boxes", inputImageCopy)
cv2.waitKey(0)
此外,我将矩形的左上角坐标、宽度和高度存储在 boundingRectangles
列表中。这是输出:
关于python - 如何裁剪图像中红点周围的固定补丁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70586598/