Sunglass Attach using CV2
Chandan Kumar Singh
System Engineer [Prime] @TCS | Ex-President & Founder @ZERO ONE Coding Club | Ex-Intern @DRDO
Introduction
Step by Step Guide
Loading Images
sunglass_image = cv2.imread("b.png", cv2.IMREAD_UNCHANGED
? ? destination_image = cv2.imread("a.jpg"))
Image
Face Detection
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
? ? gray_image = cv2.cvtColor(destination_image, cv2.COLOR_BGR2GRAY)
? ? faces = face_cascade.detectMultiScale(gray_image, scaleFactor=1.1, minNeighbors=5)
? ? if len(faces) == 0:
? ? ? ? print("No face detected in the destination image.")
? ? ? ? return
Positioning the Sunglasses
领英推荐
?sunglass_resized = cv2.resize(sunglass_image, (w, int(0.4 * h))
? ? x_offset = x
? ? y_offset = y + int(0.3 * h)
Alpha Channel Handling
?if sunglass_resized.shape[2] == 4:? # Check if sunglass image has an alpha channe 1
? ? ? ? alpha_s = sunglass_resized[:, :, 3] / 255.0
? ? ? ? alpha_d = 1.0 - alpha_s
? ? ? ? for c in range(0, 3):
? ? ? ? ? ? destination_image[y_offset:y_offset + sunglass_resized.shape[0], x_offset:x_offset + sunglass_resized.shape[1], c] = (
? ? ? ? ? ? ? ? alpha_s * sunglass_resized[:, :, c] + alpha_d * destination_image[y_offset:y_offset + sunglass_resized.shape[0], x_offset:x_offset + sunglass_resized.shape[1], c]
? ? ? ? ? ? )
? ? else:
? ? ? ? for c in range(0, 3):
? ? ? ? ? ? destination_image[y_offset:y_offset + sunglass_resized.shape[0], x_offset:x_offset + sunglass_resized.shape[1], c] = (
? ? ? ? ? ? ? ? sunglass_resized[:, :, c]
? ? ? ? ? ? )
Saving the Output
cv2.imwrite('output_image.jpg', destination_image)
Output
Feedback/Queries
I hope this article will be useful for you and that you learned something new Please, feel free to drop any questions in the comments below. I would be happy to answer them.
Thanks for reading???
Building deWall Ads | EIR fellow @iHub DivyaSampark, IIT Roorkee
1 年Really, Mind-blowing ??