import numpy as np
import cv2
#先生成一个黑色图片
img = np.zeros((512, 512, 3), np.uint8)
#画一条线
cv2.line(img, (0,0),(511,511),(255,0,0),5) #绘制一条对角线,从左上角到右下角,颜色是(255,0,0)蓝色,线条粗细:5px,(5个像素宽度)
#画矩形
cv2.rectangle(img,(384,0),(511,128),(0,255,0),5)
#画圆
cv2.circle(img,(447,63), 63, (0,0,255),5)
#画椭圆
cv2.ellipse(img,(256,256),(100,50),0,0,360,255,-1)
#绘制多边形
pts = np.array([[1,2],[100,10],[100,100],[1,150]],np.int32) #顺时针画线
pts = pts.reshape((-1,1,2)) #参数newshape = -1,表明这一维的长度是根据后面的维度计算出来的
cv2.polylines(img,[pts],True,(0,255,255)) #参数为True,得到顺次连接的闭合多边形
#在图片中绘制文字
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img,'FUCK',(10,500),font,2,(255,255,255),5)
cv2.imshow('line',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
import cv2
import numpy as np
drawing = False #鼠标按下后为True
mode = True #如果为True,画矩形。按'm'键转换为画圆
ix, iy = -1,-1
#鼠标回调函数
def draw_circle(event,x,y,flags,param):
global ix,iy,drawing,mode
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
ix,iy = x,y
elif event == cv2.EVENT_MOUSEMOVE:
if drawing == True:
if mode == True:
cv2.rectangle(img,(ix,iy),(x,y),(0,255,0),-1)
else:
cv2.circle(img,(x,y),5,(0,0,255),-1)
elif event == cv2.EVENT_LBUTTONUP:
drawing = False
if mode == True:
cv2.rectangle(img,(ix,iy),(x,y),(0,255,0),-1)
else:
cv2.circle(img,(x,y),5,(0,0,255),-1)
img = np.zeros((512,512,3), np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_circle)
while(1):
cv2.imshow('image',img)
k = cv2.waitKey(1) & 0xFF
if k == ord('m'):
mode = not mode
elif k == 27:
break
cv2.destroyAllWindows()