程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Opencv draws lines, rectangles, circles, ellipses, polygons (including polygon filling), draws text, and implements synthesis (Python Implementation)

編輯:Python

List of articles

    • 1. Draw line
    • 2. The ellipse
    • 3. Draw the circle
    • 4. Draw a rectangular
    • 5. Draw polygon
    • 6. Draw text
    • 7. Comprehensive practice

1. Draw line

line(img, pt1, pt2, color, thickness=None, lineType=None, shift=None)

Img: Input the original image ;
Pt1: Starting point coordinates ;
Pt2: End point coordinates ;
Color: Colors used ;
Thickness: The width of the line ;
lineType: The type of wire ;
Shift: Scale by coordinate ;

def drawline(img_path='images/bg.png'):
img=cv2.imread(img_path)
img=cv2.resize(src=img,dsize=(450,450))
img=cv2.line(img=img,pt1=(0,0),pt2=(350,350),color=(0,255,0),thickness=3)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()


2. The ellipse

ellipse(img, center, axes, angle, startAngle, endAngle, color, thickness=None, lineType=None, shift=None):

Img: Input the original image ;
Center: Center point coordinates ;
Axes: The length of the major axis and the minor axis ;
Angle: Select the angle counterclockwise from the center of the ellipse ;
startAngle: The angle starting clockwise ;
endAngle: Clockwise end angle ;
Color: Colors used ;
Thickness: The width of the line ;
lineType: The type of wire ;
Shift: Scale by coordinate ;

def drawellipse(img_path='images/bg.png'):
img = cv2.imread(img_path)
img = cv2.resize(src=img, dsize=(450, 450))
img = cv2.ellipse(img=img,center=(200,200),axes=(100,50),angle=0,startAngle=0,endAngle=360,color=(0,255,0),thickness=2)
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()


3. Draw the circle

circle(img, center, radius, color, thickness=None, lineType=None, shift=None):

Img: Input the original image ;
Center: The center of the circle ;
Radius: radius
Color: Colors used ;
Thickness: The width of the line (-1 Expressed as fill );
lineType: The type of wire ;
Shift: Scale by coordinate ;

def drawCircle(img_path='images/bg.png'):
img = cv2.imread(img_path)
img = cv2.resize(src=img, dsize=(450, 450))
img = cv2.circle(img=img,center=(200,200),radius=50,color=(0,255,0),thickness=3)
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()


4. Draw a rectangular

rectangle(img, pt1, pt2, color, thickness=None, lineType=None, shift=None)

Img: Input the original image ;
Pt1: Starting point coordinates ;
Pt2: End point coordinates ;
Color: Colors used ;
Thickness: The width of the line ;
lineType: The type of wire ;
Shift: Scale by coordinate ;

def drawRectangle(img_path='images/bg.png'):
img = cv2.imread(img_path)
img = cv2.resize(src=img, dsize=(450, 450))
img = cv2.rectangle(img=img,pt1=(20,20),pt2=(70,70),color=(0,255,0),thickness=3)
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()


5. Draw polygon

polylines(img, pts, isClosed, color, thickness=None, lineType=None, shift=None):

img: An image to draw a polygon on ;
pts: An array of points on a polygon ;
isClosed: Whether the drawn polygon is closed . if True , Then draw several closed polygons ; otherwise , Then draw a broken line connecting all points
color: Polygon color ;
thickness: The thickness of polygonal lines ;
lineType: The type of polygon line ;
shift: The coordinates are accurate to a few decimal places ;

def drawPolylines(img_path='images/bg.png'):
img = cv2.imread(img_path)
img = cv2.resize(src=img, dsize=(450, 450))
# Draw the point coordinates of the polygon
pts=np.array([(25,36),(89,69),(67,78),(90,128)],dtype=np.int32)
img = cv2.polylines(img=img,pts=[pts],isClosed=True,color=(0,255,0),thickness=3)
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Fill polygons

fillPoly(img, pts, color, lineType=None, shift=None, offset=None):

img: An image to draw a polygon on ;
pts: An array of points on a polygon ;
color: Polygon color ;
thickness: The thickness of polygonal lines ;
lineType: The type of polygon line ;
shift: The coordinates are accurate to a few decimal places ;
Offset: An optional offset for all points of the offset contour ;

def drawPolylineFulls(img_path='images/bg.png'):
img = cv2.imread(img_path)
img = cv2.resize(src=img, dsize=(450, 450))
# Draw the point coordinates of the polygon
pts=np.array([(25,36),(89,69),(67,78),(90,128)],dtype=np.int32)
img=cv2.fillPoly(img=img,pts=[pts],color=(0,255,0))
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()


6. Draw text

putText(img, text, org, fontFace, fontScale, color, thickness=None, lineType=None, bottomLeftOrigin=None)

Img: Input the original image ;
Text: Drawn text ;
Org: The starting point of drawing ;
color: Polygon color ;
thickness: The thickness of polygonal lines ;
lineType: The type of polygon line ;
bottomLeftOrigin: If true, The origin of image data is in the lower left corner . otherwise , It will be in the upper left corner .

def drawPutText(img_path='images/bg.png'):
img = cv2.imread(img_path)
img = cv2.resize(src=img, dsize=(450, 450))
cv2.putText(img=img,text='Scientist',org=(20,50),fontFace=cv2.FONT_HERSHEY_SIMPLEX,fontScale=2,color=(0,255,0),thickness=2)
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()


7. Comprehensive practice

# Press the left mouse button to start drawing , After the left key is released, draw a figure .
# Press down q Key to exit , Press down L Key draw line , Press down R Key draw rectangle , Press down C Key word circle , Press down E Key means to draw an ellipse

import os
import cv2
import numpy as np
curshape=0
startpos=(0,0)
endspos=(0,0)
# create a window
cv2.namedWindow(winname='drawindow',flags=cv2.WINDOW_AUTOSIZE)
# Create a white background
def whiteimage(img):
B,G,R=cv2.split(img)
B[:]=255
G[:]=255
R[:]=255
mergeImage=cv2.merge((B,G,R))
return mergeImage
img=np.zeros(shape=(300,450,3),dtype=np.uint8)
img=whiteimage(img)
# obtain TrackBar Value
def TrackBarValue():
# Get the window “window” Child window “R” Value
value_R= cv2.getTrackbarPos(trackbarname='R', winname='drawindow')
value_G = cv2.getTrackbarPos(trackbarname='G', winname='drawindow')
value_B = cv2.getTrackbarPos(trackbarname='B', winname='drawindow')
return (value_R,value_G,value_B)
# Define callback function
def callback():
pass
# Definition TrackBar function
def TrackBarBGR():
#value-trackbar Value count- Maximum value set count( The minimum value is 0) OnChange- Callback function 
cv2.createTrackbar('R','drawindow', 0, 255, callback)
cv2.createTrackbar('G','drawindow', 0, 255, callback)
cv2.createTrackbar('B','drawindow', 0, 255, callback)
TrackBarBGR()
# Callback function definition
def mouse_callback(event,x,y,flags,userdata):
global startpos
global endspos
global curshape
if (event&cv2.EVENT_LBUTTONDOWN==cv2.EVENT_LBUTTONDOWN):
startpos=(x,y)
elif (event&cv2.EVENT_LBUTTONUP==cv2.EVENT_LBUTTONUP):
endspos=(x,y)
if curshape==0:
cv2.line(img=img,pt1=startpos,pt2=endspos,color=TrackBarValue(),thickness=3)
elif curshape==1:
cv2.rectangle(img=img,pt1=startpos,pt2=endspos,color=TrackBarValue(),thickness=3)
elif curshape==2:
a=(endspos[0]-startpos[0])
b=(endspos[1]-startpos[1])
radis=np.int32((a**2+b**2)**0.5)
cv2.circle(img=img,center=startpos,radius=radis,color=TrackBarValue(),thickness=3)
elif curshape==3:
a = (endspos[0] - startpos[0])
b = (endspos[1] - startpos[1])
cv2.ellipse(img=img,center=startpos,axes=(a,b),angle=0,startAngle=0,endAngle=360,color=TrackBarValue(),thickness=3)
if (event&cv2.EVENT_LBUTTONDBLCLK==cv2.EVENT_LBUTTONDBLCLK):
text=input(' Please enter text : ')
cv2.putText(img=img,text=text,org=startpos,fontFace=cv2.FONT_HERSHEY_SIMPLEX,fontScale=2,color=TrackBarValue(),thickness=2)
# Set the mouse callback function
cv2.setMouseCallback('drawindow',mouse_callback)
while True:
cv2.imshow('drawindow',img)
# Press down q Key to exit , Press down L Key draw line , Press down R Key draw rectangle , Press down C Key word circle , Press down E Key means to draw an ellipse , Press down W Key to draw text
key=cv2.waitKey(1)
if key==ord('q'):
break
elif key==ord('l'):
curshape=0
elif key==ord('r'):
curshape=1
elif key==ord('c'):
curshape=2
elif key==ord('e'):
curshape=3
elif key==ord('w'):
curshape=4
cv2.destroyAllWindows()
if __name__ == '__main__':
print('Pycharm')

Mouse events can be seen from this blogger :
https://blog.csdn.net/qq_55025358/article/details/124067576


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved