Skip to content

Instantly share code, notes, and snippets.

@dalelane
Created January 25, 2019 09:37
Show Gist options
  • Select an option

  • Save dalelane/72c14aa4e6ac54626c4609beeeaf7c81 to your computer and use it in GitHub Desktop.

Select an option

Save dalelane/72c14aa4e6ac54626c4609beeeaf7c81 to your computer and use it in GitHub Desktop.
import requests
import image_slicer
# Gets the contents of an image file to be sent to the
# machine learning model for classifying
def getImageFileData(locationOfImageFile):
with open(locationOfImageFile, "rb") as f:
data = f.read()
return data.encode("base64")
# This function will pass your image to the machine learning model
# and return the top result with the highest confidence
def classify(imagefile):
key = "MY-API-KEY"
url = "https://machinelearningforkids.co.uk/api/scratch/"+ key + "/classify"
response = requests.post(url, json={ "data" : getImageFileData(imagefile) })
if response.ok:
responseData = response.json()
topMatch = responseData[0]
return topMatch
else:
response.raise_for_status()
def chopImageIntoBits(imagefile):
return image_slicer.slice(imagefile, 14)
imageSegments = chopImageIntoBits("my-image-file.jpg")
for imageSegment in imageSegments:
results = classify(imageSegment.filename)
topleftX = imageSegment.coords[0]
topleftY = imageSegment.coords[1]
width = imageSegment.image.size[0]
height = imageSegment.image.size[1]
label = results["class_name"]
confidence = results["confidence"]
print ("section of image %dx%d starting at %d,%d (file name %s)" % (width, height, topleftX, topleftY, imageSegment.filename))
print (" result : '%s' with %d%% confidence" % (label, confidence))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment