img_to_path / img_to_path_outline.pyon commit add dlw module; clean up for handover (d7cac70)
   1"""
   2img_to_path_outline.py
   3Andrew Lorimer, November 2024
   4Monash University
   5
   6Extracts contours (outlines) from a monochrome image, converts to a series of 
   7points representing straight lines, and outputs these points in the 
   8appropriate format for laser writing with the confocal setup. For use with 
   9LabView script.
  10"""
  11
  12import cv2
  13import numpy as np
  14import sys
  15
  16SPEED = 100         # um/s
  17REAL_DIM = 100.0    # um
  18Z = 0.0             # um
  19
  20np.set_printoptions(threshold=sys.maxsize)
  21
  22def row(x, y, z, on, t):
  23    return "1\t{:.3f}\t{:.3f}\t{:.3f}\t{:.3f}\t{:d}\n".format(x, y, z, on, t)
  24
  25
  26im = cv2.imread('test_img/test_img_1.png', cv2.IMREAD_GRAYSCALE)
  27dim = im.shape
  28
  29if (dim[0] != dim[1]):
  30    print("Error: image must be square")
  31    sys.exit()
  32
  33output = ""
  34
  35# Go to origin point (laser off)
  36output += row(0.0, 0.0, Z, 0.0, SPEED)
  37
  38result_fill = np.ones(dim, np.uint8) * 255
  39result_borders = np.zeros(dim, np.uint8)
  40
  41# the '[:-1]' is used to skip the contour at the outer border of the image
  42contours = cv2.findContours(im, cv2.RETR_LIST,
  43                            cv2.CHAIN_APPROX_SIMPLE)[0][:-1]
  44
  45print(len(contours))
  46print(contours[-1][:10])
  47print(contours[0].shape)
  48
  49cv2.drawContours(result_fill, contours, -1, 0, -1)
  50cv2.drawContours(result_borders, contours, -1, 255, 1)
  51
  52for contour in contours:
  53    for i, point in enumerate(contour):
  54        point_real = point[0] / dim[0] * REAL_DIM
  55        laser_on = 0.0 if i == 0 else 1.0
  56        output += row(point_real[0], point_real[1], Z, laser_on, SPEED)
  57
  58output += row(0.0, 0.0, Z, 0.0, SPEED)
  59
  60with open('path.txt', 'w') as f:
  61    f.write(output)
  62
  63
  64# Questions
  65# Thickness of lines
  66# Stage uncertainty/increment
  67# Sample dimensions
  68# Dwell time