current position:Home>Learning in Python + opencv -- extracting corners

Learning in Python + opencv -- extracting corners

2022-01-30 02:33:20 kobesdu

Realize the function of extracting contour , And draw the center of gravity of the outline

import numpy as np

import cv2

from pylab import imshow

from pylab import array

from pylab import plot

from pylab import title

# Read the picture

img = cv2.imread('timg.jpeg')

img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)# To gray value

# Two valued ,canny testing

binaryImg = cv2.Canny(img,50,200)

# Look for the outline

contours,contourstype=cv2.findContours(binaryImg,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

# Check the number of contours

-- print (len(contours))

--print (type(contours))

-- print (type(contourstype))

--print ((contourstype))

temp = np.ones(binaryImg.shape,np.uint8)*255

for each in contours:

M = cv2.moments(each)# Moment of contour 
 Copy code 

( stay OpenCV in , It is very convenient to calculate the of polygon area 3 First order characteristic moment ,opencv The moments in mainly include the following : Space moment , Central moment and central normalized moment .)

if (M['m00']!=0):

    cx = int(M['m10']/M['m00'])# Calculate the center of gravity 
    
    cy = int(M['m01']/M['m00'])
    
    pos=(cx,cy)
    
    print(pos)
    
cv2.circle(temp,pos, 4, (0, 0, 0), 4)# Draw the center point of the contour 

(img Pointer to the source image ; The first parameter is the coordinates of the center of the circle ; The second parameter is the radius of the circle ; The third is to set the color of the circle , Rule basis B( blue )G( green )R( red ) The fourth one s If the parameter is a positive number , Indicates the thickness of the lines that make up the circle . otherwise , Indicates whether the circle is filled )
 Copy code 

# Draw the outline :temp It's a white curtain ,contours It's the outline ,-1 It means the whole picture , Then the color , The thickness of the

cv2.drawContours(temp,contours,-1,(0,255,0),3)

( Draw external and internal contours in the image ; Among them, Dangdang thickness >= 0 when , Draw contours ; Otherwise, fill the part surrounded by the contour ..)

cv2.imshow("contours",temp)

cv2.waitKey(0)

cv2.destroyAllWindows()

About drawContours Reference resources blog.csdn.net/fulva/artic… About drawing circle function reference blog.csdn.net/yangfengman…

copyright notice
author[kobesdu],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201300233183693.html

Random recommended