Detect and Highlight Red Apples (Color Detection)

This will detect red apples and draw green bounding box around them.

In [1]:
import cv2
import numpy as np
from google.colab.patches import cv2_imshow

# Load image
image = cv2.imread("harry_potter_red.jpg")

# Convert to HSV
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

# Red color ranges
lower_red1 = np.array([0, 120, 70])
upper_red1 = np.array([10, 255, 255])

lower_red2 = np.array([170, 120, 70])
upper_red2 = np.array([180, 255, 255])

# Create mask
mask1 = cv2.inRange(hsv, lower_red1, upper_red1)
mask2 = cv2.inRange(hsv, lower_red2, upper_red2)

mask = mask1 + mask2

# Clean noise
kernel = np.ones((5,5), np.uint8)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)

# Find contours
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

for cnt in contours:
    area = cv2.contourArea(cnt)
    if area > 500:   # ignore small noise
        (x,y,w,h) = cv2.boundingRect(cnt)
        cv2.rectangle(image, (x,y), (x+w,y+h), (0,255,0), 2)

cv2_imshow(image)
In [2]:
###Make Only Apples Color — Rest Black & White (Cool Demo)
# Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)

result = np.where(mask[:,:,None]==255, image, gray)

cv2_imshow(result)
In [3]:
###Face detection
face_cascade = cv2.CascadeClassifier(
    cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray_img, 1.3, 5)

for (x,y,w,h) in faces:
    cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,0),2)

cv2_imshow(image)
In [4]:
###Blur Background Only
blur = cv2.GaussianBlur(image, (35,35), 0)

# Invert mask (non-red areas)
mask_inv = cv2.bitwise_not(mask)

background = cv2.bitwise_and(blur, blur, mask=mask_inv)
foreground = cv2.bitwise_and(image, image, mask=mask)

final = cv2.add(background, foreground)

cv2_imshow(final)
In [4]: