OpenCV 3 Computer Vision with Python Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

  1. Open an image and get its width and height. Also, define a simple function that returns a random point inside our image:
import cv2, random

image = cv2.imread('../data/Lena.png')
w, h = image.shape[1], image.shape[0]


def rand_pt(mult=1.):
return (random.randrange(int(w*mult)),
random.randrange(int(h*mult)))
  1. Let's draw something! Let's go for circles:
cv2.circle(image, rand_pt(), 40, (255, 0, 0))
cv2.circle(image, rand_pt(), 5, (255, 0, 0), cv2.FILLED)
cv2.circle(image, rand_pt(), 40, (255, 85, 85), 2)
cv2.circle(image, rand_pt(), 40, (255, 170, 170), 2, cv2.LINE_AA)
  1. Now let's try to draw lines:
cv2.line(image, rand_pt(), rand_pt(), (0, 255, 0))
cv2.line(image, rand_pt(), rand_pt(), (85, 255, 85), 3)
cv2.line(image, rand_pt(), rand_pt(), (170, 255, 170), 3, cv2.LINE_AA)
  1. If you want to draw an arrow, use the arrowedLine() function:
cv2.arrowedLine(image, rand_pt(), rand_pt(), (0, 0, 255), 3, cv2.LINE_AA)
  1. To draw rectangles, OpenCV has the rectangle() function:
cv2.rectangle(image, rand_pt(), rand_pt(), (255, 255, 0), 3)
  1. Also, OpenCV includes a function to draw ellipses. Let's draw them:
cv2.ellipse(image, rand_pt(), rand_pt(0.3), random.randrange(360), 0, 360, (255, 255, 255), 3)
  1. Our final drawing-related function is for placing text on the image:
cv2.putText(image, 'OpenCV', rand_pt(), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 3)