Last active
August 29, 2015 14:27
-
-
Save jacobbrunson/17c17dd45b8fbeafe9d2 to your computer and use it in GitHub Desktop.
Analyzing Crop Yields By Drone (in Python!)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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