Written By:
Trilochan Tarai
OpenCV is a python library of programming functions which mainly aimed at real-time computer vision.
Originally developed by Intel, it was later supported by Willow Garage then Itseez. The library is cross-platform and free for use under the open-source BSD license.
How to install OpenCV
Open anaconda command prompt and run the following command:
pip install opencv-python
#To import opencv library
import cv2
#To know the version of opencv
print(cv2.__version__)
4.2.0
Basic Operations with OpenCV
#How opencv read an image
img=cv2.imread("E:\\silan\\amir.jpg",1)
print(type(img))
Output : <class 'numpy.ndarray'>
img=cv2.imread("E:\\silan\\amir.jpg",1)
print(img)
print(img.shape)
Output : (608, 612, 3)
#To display the image
cv2.imshow("icfai",img)
cv2.waitKey(0)
cv2.destroyAllWindows()
#Resizing the image
resized=cv2.resize(img,(600,600))
cv2.imshow("bjd",resized)
cv2.waitKey(2000)
cv2.destroyAllWindows()
Here, resize function is used to resize an image to the desired shape. The parameter here is the shape of the new resized image.
Face Detection Using OpenCV
Now we will see to detect a face from an image using OpenCV. So let’s follow the following steps:
Step 1: Considering our prerequisites, we will require an image, to begin with. Later we need to create a cascade classifier which will eventually give us the features of the face.
Step 2: This step involves making use of OpenCV which will read the image and the features file. So at this point, there are NumPy arrays at the primary data points.
All we need to do is to search for the row and column values of the face NumPy ndarray. This is the array with the face rectangle coordinates.
Step 3: This final step involves displaying the image with the rectangular face box.
import cv2
# Create a CascadeClassifier Object
face_cascade = cv2.CascadeClassifier("C:/Users/hp/Anaconda3/Lib/site-packages/cv2/data/haarcascade_frontalface_default.xml")
# Reading the image as it is
img = cv2.imread("E:\\silan\\silu.jpg")
# Reading the image as gray scale image.
gray_img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# Search the co-ordintes of the image.
faces = face_cascade.detectMultiScale(gray_img, scaleFactor = 1.05, minNeighbors=5)
print(type(faces))
print(faces)
for x,y,w,h in faces:
img = cv2.rectangle(img, (x,y), (x+w,y+h),(255,0,0),3)
resized = cv2.resize(img, (int(img.shape[1]/7),int(img.shape[0]/7)))
cv2.imshow("Gray", resized)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output:
[[123 64 144 144]]
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc