SoFunction
Updated on 2024-11-17

Example of opencv image contour implementation

image profile

Contours.
Contouring is connecting edges that are not connected together.
Edge detection detects edges, which are somewhat unconnected.


caveat
1. The object is a binary image, first threshold segmentation or edge detection.
2. Finding outlines requires changes to the original image, usually using a copy of the original image to make a copy.
3. In opencv, it's white from a black background. So the object must be white with a black background.

methodologies

  • ()
  • ()

Find out where the outline is with (), then draw the found outline with ().

contours,hierarchy=(image,mode,method)
contours: contours
hierarchy: topological information (hierarchy of contours) of the image (stores previous contour, parent contour...)
image: original image
mode:Outline search mode
method:Approximation method for contours


r=(image, contours, contourIdx, color[, thickness])

r:target image
image:Original image
contours: array of all input contour edges
contourIdx : the index of the edge to be drawn, -1 if all are drawn. if there are more than one target, the first target 0, the second target 1, the third target 2... can be drawn.
color: the color of the drawing, SCalar in BGR format.
thickness: optional, the density of the drawing, i.e. the thickness of the brush for the contour.

import cv2
import numpy as np
o = ('')
gray = (o,cv2.COLOR_BGR2GRAY)#BGR-Gray Scale
ret, binary = (gray,127,255,cv2.THRESH_BINARY)#Binary images
contours, hierarchy = (binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
co=()# Plotting the original image
r=(co,contours,-1,(0,127,127),4)#co is a copy of the image, the outline modifies the original image
("original",o)
("contours",r)
()


(input_image, flag) is used for color space conversion.
input_image: the image to be converted
flag:Conversion type
cv2.COLOR_BGR2GRAY : BGR - gray scale
cv2.COLOR_BGR2RGB:BGR-RGB
cv2.COLOR_BGR2HSV:BGR-HSV

least outer circle

The function() helps us find the exterior tangent circle of an object. It is the smallest area of all the circles that can include the object.

Example: A picture such as the one below is available, and you are asked to mark the flower in the center of the picture.

Code:

import numpy as np
import cv2 as cv

img=("",0)

# Scale the image here for ease of display
x,y=
img=(img,(y//2,x//2))
# Binarize the image, since the foreground object is black, use cv.THRESH_TOZERO_INV for binarization.
ret,thresh=(img,127,255,cv.THRESH_TOZERO_INV)
#Find contours in the image, mode=cv.RETR_EXTERNAL, this is to find the outermost contours
im,contour,hierarchy=(thresh,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)

The # function's arguments require the ndarray type, so here will be the found
# Store all the points in the profile in a list and use this list to create an array.
point_list=[]
for i in contour:
  for j in i:
    point_list.append(j[0])
point_array=(point_list)

# Use the minimum outer circle function, the return value is the center of the circle and the length of the circle radius.
(x,y),radius=(point_array)

# The coordinates on the image are all integers, and the radius of the circle is also required to be an integer, so force them to be converted to int type
center=(int(x),int(y))
color=(img,cv.COLOR_GRAY2BGR)
color=(color,center,radius=int(radius),color=(0,0,255),thickness=2)
#Display Pictures
("color",color)
(0)
()

Program Results:

bunghole

Convex packets and contours are approximately similar, but different, although in some cases they give the same result. The function() can be used to detect if a curve has a convexity defect and can correct the defect. In general, convex curves are always convex, or at least flat. The function is used in opencv to find convex packets of a contour, which is defined as:

hull=( points[, hull[, clockwise[, returnPoints]]])

The parameters of this function are as follows:

Points: the profile we need to pass in

Hull: output, usually not needed

clockwise: Orientation flag, if True, the direction of the bump is clockwise, otherwise counterclockwise;

returnPoints: defaults to True. It will return the coordinates of the points on the convex envelope. If set to False, it will return the points on the contour that correspond to the bump points.

Or this picture above, we can get the shape of the convex bag by slightly modifying the code above, the code is as follows:

import numpy as np
import cv2 as cv

img=("",0)

# Scale the image here for ease of display
x,y=
img=(img,(y//2,x//2))
# Binarize the image, since the foreground object is black, use cv.THRESH_TOZERO_INV for binarization.
ret,thresh=(img,127,255,cv.THRESH_TOZERO_INV)
#Find contours in the image, mode=cv.RETR_EXTERNAL, this is to find the outermost contours
im,contour,hierarchy=(thresh,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)

The # function's arguments require the ndarray type, so here will be the found
# Store all the points in the profile in a list and use this list to create an array.
point_list=[]
for i in contour:
  for j in i:
    point_list.append(j[0])
point_array=(point_list)

# Find convex packets, return value is a point on the convex packet
hull=(point_array,returnPoints=True)
color=(img,cv.COLOR_GRAY2BGR)

# Plot the convex packet, with a caveat: here you need to write the coordinates of the points on the convex packet as a
The #list is passed into the function, otherwise all that is plotted is a series of points on the convex bag
color=(color,[hull],True,(0,0,255),2)
#Display Pictures
("color",color)
(0)
()

The result of running the program is:

Image masks and pixels

Sometimes we need all the pixel points that make up an object, we can extract all the outlines of the image and then use the function () to fill the area within the outlines with the specified color. Then use the () function to extract the coordinates of the non-zero pixel points so that we get the pixel points that make up the object. We are still working on the above image and the code is as follows:

import numpy as np
import cv2 as cv

img=("",0)

# Scale the image here for ease of display
x,y=
img=(img,(y//2,x//2))
# Binarize the image, since the foreground object is black, use cv.THRESH_TOZERO_INV for binarization.
ret,thresh=(img,127,255,cv.THRESH_TOZERO_INV)
#Find contours in the image, mode=cv.RETR_EXTERNAL, this is to find the outermost contours
im,contour,hierarchy=(thresh,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)
#Create a drawing board filled with pixel points inside the outline, with a black background color, here we use numpy to create a two-dimensional array of all zeros
mask=(,dtype=np.uint8)
# Set the parameter thickness to -1 so that the function fills the pixel points within the outline with the specified color
mask=(mask,contour,contourIdx=-1,color=(255,255,255),thickness=-1)

# Find non-zero pixel points within the mask and store them as a numpy array
NonZeroPoints=((mask))
#ShapeTransform, changing it to a two-dimensional array with each row of the array holding the coordinates of a non-zero pixel point
NonZeroPoints=((-1,2))
# Verify that the coordinates of our extracted pixel points are correct, we use the variable
#column and row hold the number of columns and rows, respectively, of non-zero pixel points at coordinates in the image
column=NonZeroPoints[:,0]
row=NonZeroPoints[:,1]
# Plot these points on a new drawing board, setting the values of the pixel points corresponding to these coordinates to 255
mask1=()
mask1[row,column]=255
# Show results
("mask",mask)
("mask1",mask1)
(0)
()

Program run results:

By comparing the results of the two images above, we can see that: the constituent pixel points of the object are correctly extracted.

to this article on the realization of the opencv image contour example of the article is introduced to this, more related to the content of the opencv image contour please search for my previous articles or continue to browse the following related articles I hope that you will support me more in the future!