Detect Ripe Fruit in 5 Minutes with OpenCV

James Thesken
2 min readAug 21, 2017

--

You’ve just been approached by a multi-million dollar apple orchard to create an automated picking machine. Panic. Or crack open a cold one and install the popular computer vision library OpenCV. Easy. Let’s get started.

They’re right there, what’s the big deal?

So we have our image of some apples up there, let’s cook something up to show our idea. First we’ll call our dependencies:

#Standard imports
import cv2
import numpy as np

Next we read the image and shift our color space from BGR to HSV:

#Read image
image = cv2.imread("apples.jpg")
#Convert BGR to HSV
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

HSV has three components of hue, saturation, and value. We go to our favorite color-wheel website and grab the upper and lower bounds of the color we would like to detect. In this case, we choose the values from yellow/red-ish to completely red. We create a numpy array containing these values:

#Color strength parameters in HSV
weaker = np.array([0,0,100])
stronger = np.array([10,255,255])

Alright, one more step and we’ll become millionaires. Threshold the image to only display color in the range we just defined. We use the function cv2.inRange with the parameters being our hsv image and defined range:

#Threshold HSV image to obtain input color
mask = cv2.inRange(hsv, weaker, stronger)
#Show original image and result
cv2.imshow('Image',image)
cv2.imshow('Result',mask)
#Press any key to exit
cv2.waitKey(0)
cv2.destroyAllWindows()

Run that in your favorite IDE or straight up in the terminal if you’re running Linux. The result should look something like this, depending on what fruit you’re looking for!

An apple a day…

This was a baby step of course, but I hope to have passed on some excitement and maybe some ideas of how to use this library! Your next step: use edge detection and regions of interest to display a box around the detected fruit. Post your GitHub links in the comments!

-James

--

--

James Thesken

Mechanical engineer from Hawaii. Enjoys surfing and larp-ing as a software developer. ||| website: jamesthesken.github.io |||