#! /usr/bin/python3 # Last edited on 2021-03-02 12:00:42 by jstolfi # Reads a bunch of egg images and adusts a mean contour. import numpy as np import cv2 as cv from matplotlib import pyplot as plt import sys import math show_in = False show_gr = False show_hg = False show_tr = False imdir = sys.argv[1] imname = sys.argv[2] # Read the image img_in = cv.imread('in/%s/%s.png' % (imdir,imname)) if show_in: cv.imshow('img_in',img_in) cv.waitKey(0) # Compute the histogram of the red channel: hist_in = cv.calcHist([img_in], [0], None, [512], [0,512]) if show_hg: aplt.plot(hist_in) plt.show() # Convert image to grayscale: img_gr = cv.cvtColor(img_in, cv.COLOR_BGR2GRAY) img_gr = cv.blur(img_gr, (3,3)) if show_gr: cv.imshow('img_gr',img_gr) cv.waitKey(0) # Threshold the image: ret, img_tr = cv.threshold(img_gr, 190, 255, cv.THRESH_BINARY_INV) if show_tr: cv.imshow('img_tr',img_tr) cv.waitKey(0) # Extract the contour contours, hierarchy = cv.findContours(img_tr, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE) nc = len(contours) sys.stderr.write("found %d contours\n" % nc) assert nc == 1 # Write the points of the contour: wr = open('out/%s-pts.txt' % imname, 'w') szy, szx = img_tr.shape pts = [] for k in range(nc): ctk = contours[k] npk = len(ctk) sys.stderr.write(" contour %d has %d points\n" % (k,npk)) for i in range(npk): ptki = ctk[i] # sys.stderr.write(" ct[%d][%d] = %s\n" % (k,i,str(ptki))) xki = ptki[0][0] yki = szy - ptki[0][1] wr.write("%6d %6d %6d\n" % (i,xki,yki)) pts.append((xki,yki)) wr.write("\n") wr.close()