python - 如何裁剪图像中红点周围的固定补丁

标签 python python-3.x opencv image-processing computer-vision

我是 OpenCV 的新手,我什至不确定如何解决这个问题。我有这张 500x500 像素的图片,里面有红点和白线。

enter image description here

以每个红点为中心,我可以在红点周围绘制一个 25X25 大小的固定边界框吗?我需要识别图像中的每个红点。

enter image description here

注意:条件是我需要找到一个固定大小(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 列表中。这是输出:

enter image description here

关于python - 如何裁剪图像中红点周围的固定补丁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70586598/

相关文章:

python - 使用 python 缩小我从网站上抓取的内容

python - Tensorflow 多 GPU - NCCL

python - PyPDF2 不会从 PDF 中提取所有文本

python-3.x - 为什么 'if not None' 返回 True?

python - numpy 2d 数组(坐标)需要分配到 3D 数组中,分配给某个特定的 bin

opencv - OpenCV摄像机校准结果每次都不同

c++ - OpenCV 绘图边界框 CenterPoint

python - 如何使用gdata python库从youtube获取所有视频的列表

python - Python 中多个数组的最大值和最小值

Python 扩展 - 有效地构造和检查大整数