一、畫線、圓、橢圓、多邊形、文字
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()
切換到m