Sunday, November 22, 2015

OpenCV: Using cv2.minMaxLoc to find the darkest and brightest region in an image

#Using cv2.minMaxLoc to find the darkest and brightest region in an image
#OpenCV 3.0.0
#Raspberry Pi 2, Jessie

#Must have an image in the same directory as this program.
#Enter the following on the command line:
#$python brightspot.py --image name.jpg --radius 21    #radius must be odd number

### Import the necessary packages
import numpy as np
import argparse
import cv2

### Construct the argument parse and parse the arguments
ap      = argparse.ArgumentParser()
ap.add_argument("-i", "--image", help = "path to the image file")
ap.add_argument("-r", "--radius", type = int,
        help = "radius of Gaussian blur; must be odd")
args    = vars(ap.parse_args())

### Load the image
image   = cv2.imread(args["image"])                             #load the image
### Resize the image (may not be necessary if your images is already a reasonable size).
r       = 500.0 / image.shape[1]                                #calculate r, ratio of new width to old width
dim     = (500, int(image.shape[0] * r))                        #dimension = x pixels by r times the height to keep aspect ratio
image   = cv2.resize(image, dim, interpolation = cv2.INTER_AREA)

### Convert to grayscale
gray    = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)               #convert to gray
### Apply a Gaussian blur to the image
gray    = cv2.GaussianBlur(gray, (args["radius"], args["radius"]), 0)
### Find the darkest and brightest region
(minVal, maxVal, minLoc, maxLoc) = cv2.minMaxLoc(gray)
### Draw circles around the darkesst and brightest region
cv2.circle(image, maxLoc, args["radius"], (0, 0, 255), 2)       #draw a circle around the bright area
cv2.circle(image, minLoc, args["radius"], (0, 255, 0), 2)       #draw a circle around the dark area

### Display the results to the screen
cv2.imshow("Gray", gray)
cv2.imshow("Robust", image)
cv2.waitKey(0)

No comments:

Post a Comment

Be nice!