Skip to content

Instantly share code, notes, and snippets.

@jacobbrunson
Last active Aug 29, 2015
Embed
What would you like to do?
Analyzing Crop Yields By Drone (in Python!)
# Based on the Mathematica blog post: http://community.wolfram.com/groups/-/m/t/551187
# Screenshot: http://i.imgur.com/caMxnBl.png
from sklearn.cluster import KMeans
import numpy as np
import cv2
img = cv2.imread("crops.png")
img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
pixels = img.reshape((img.shape[0] * img.shape[1], 3))
clt = KMeans(n_clusters=10)
clt.fit(pixels)
dominant_color = clt.cluster_centers_[np.argmax(np.bincount(clt.labels_))]
distances = np.sqrt(np.sum((img-dominant_color)**2, axis=-1))
normalized = (255 - distances/np.max(distances)*255).astype("uint8")
ret, binary = cv2.threshold(normalized, 180, 255, cv2.THRESH_BINARY)
soy_pixels = cv2.countNonZero(binary)
total_pixels = len(pixels)
print "Crop yield: %.2f%%" % (float(soy_pixels) / total_pixels * 100)
cv2.imshow("Soy Pixels", binary)
cv2.waitKey(0)
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment