SoFunction
Updated on 2024-11-16

Python Opencv Arbitrarily Shaped Target Detection and Drawing Block Diagrams

opencv for arbitrary shape target recognition, for your reference, is as follows

There was a time at work when I needed to perform target recognition on a simple graph, where the shape of the target was not fixed and there was some degree of noise influence, but the noise influence was indeterminate. It was a simple matter as the image was not complex and the code is now published below:

import cv2


def otsu_seg(img):

  ret_th, bin_img = (img, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)

  return ret_th, bin_img

def find_pole(bin_img):
  img, contours, hierarchy = (bin_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  area = 0
  for i in range(len(contours)):
    area += (contours[i])
  area_mean = area / len(contours)
  mark = []
  for i in range(len(contours)):
    if (contours[i]) < area_mean:
      (i)

  return img, contours, hierarchy, mark

def draw_box(img,contours):
  img = (img,
         (contours[0][0], contours[0][1]),
         (contours[1][0], contours[1][1]),
         (255,255,255),
         3)
  return img

def main(img):
  ret, th = otsu_seg(img)
  img_new, contours, hierarchy, mark = find_pole(th)
  for i in range(len(contours)):
    if i not in mark:
      left_point = contours[i].min(axis=1).min(axis=0)
      right_point = contours[i].max(axis=1).max(axis=0)
      img = draw_box(img, (left_point, right_point))
  return img


if __name__ =="__main__":
  img = ('G:/')
  img = main(img)
  ('G:/test_d.png', img)

The resulting graph is shown below:

This is the whole content of this article.