简体   繁体   English

如何在图像中的点周围绘制正方形

[英]How to draw a square around the points in the image

I have a binary image, with white points. 我有一个带有白色点的二进制图像。 How can I identify and draw a square around these points using OpenCV? 如何使用OpenCV识别并在这些点周围绘制正方形?

The problem is that the points are very small, and so far all the attempts have failed to find all the points. 问题在于这些点非常小,到目前为止,所有尝试都未能找到所有点。

This is the input image: 这是输入图像: bin图像

This is the result I am interested in: 这是我感兴趣的结果: 出色的结果

Is there a possibility using a function of OpenCV? 是否可以使用OpenCV功能? And if not, (because of size), what is the most effective way? 如果不是(由于大小),最有效的方法是什么?

  1. Apply dilate on your image with size 5. 应用扩张与规模5图像上。

  2. If distance of between dots < 10, they will be joined to one big dot. 如果点之间的距离<10,它们将连接到一个大点。

  3. If distance > 10, it will be seperated as it is. 如果距离> 10,则将按原样分隔。

  4. Find contours on result. 在结果上找到轮廓

  5. Get minAreaRect of each contours. 获取每个轮廓的minAreaRect

  6. Done. 完成。

Using following method you can find a solution. 使用以下方法,您可以找到解决方案。

Full code for the solution: 解决方案的完整代码:

import cv2
import numpy as np
img = cv2.imread('test.jpg', 0)
output_img = img.copy()
cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU,img)

kernel = np.ones((50,70), np.uint8)
img = cv2.dilate(img, kernel, iterations=1)


im2,contours, hier = cv2.findContours(img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
    # get the bounding rect
    x, y, w, h = cv2.boundingRect(c)
    # draw a white rectangle to visualize the bounding rect
    cv2.rectangle(output_img, (x, y), (x + w, y + h), 255, 1)

cv2.imshow('output',output_img)
cv2.waitKey(0)
  • First you have to create a kernel according to your requirement. 首先,您必须根据需要创建一个内核。

  • Bigger the kernel size, points belong to a cluster will be higher. 内核大小越大,属于群集的点数就会越高。

  • Then using cv2.dilate method you should dilate the image using created kernel. 然后,使用cv2.dilate方法,应该使用创建的内核来cv2.dilate图像。

  • After that you should find contours of dilated image and get the bounding rectangle of those contours. 之后,您应该找到膨胀图像的轮廓,并获得这些轮廓的边界矩形。

  • One rectangle can be considered as one cluster. 一个矩形可以视为一个群集。 You can change the cluster size using kernel = np.ones((50,70), np.uint8) In here it is 50 x 70. 您可以使用kernel = np.ones((50,70), np.uint8)更改群集大小kernel = np.ones((50,70), np.uint8)此处为50 x 70。

OUTPUT: OUTPUT:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM