vectorized an image in python

To vectorize an image in python, we can use the OpenCV library in conjunction with NumPy. The basic steps are:

  1. Load the image using the cv2.imread() method
  2. Convert the image from a 3-channel BGR color space to a single-channel grayscale image
  3. Apply any necessary image preprocessing methods (e.g. thresholding) to enhance edges
  4. Use the cv2.Canny() method to detect edges in the image
  5. Apply the cv2.findContours() method to find contours in the edge image
  6. Convert each contour to a polygon using the cv2.approxPolyDP() method
  7. Draw the polygons on a blank image using the cv2.drawContours() method

Here's some sample code that demonstrates this process:

main.py
import cv2
import numpy as np

# Load the image
img = cv2.imread('image.jpg')

# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Preprocess the image
blur = cv2.GaussianBlur(gray, (5, 5), 0)
thresh = cv2.threshold(blur, 60, 255, cv2.THRESH_BINARY)[1]

# Detect edges
edges = cv2.Canny(thresh, 100, 200)

# Find contours
contours, hierarchy = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Convert contours to polygons
polygons = []
for contour in contours:
    epsilon = 0.01*cv2.arcLength(contour,True)
    approx = cv2.approxPolyDP(contour,epsilon,True)
    polygons.append(approx)

# Draw polygons on a blank image
vectorized = np.zeros_like(img)
cv2.drawContours(vectorized, polygons, -1, (255,255,255), 3)

# Display the vectorized image
cv2.imshow('Vectorized Image', vectorized)
cv2.waitKey(0)
cv2.destroyAllWindows()
870 chars
35 lines

This code will display a window with the original image and a window with the vectorized image overlaid on a black background.

gistlibby LogSnag