使用Python中的OpenCV从图像中裁剪面
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了使用Python中的OpenCV从图像中裁剪面,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2052字,纯文字阅读大概需要3分钟。
内容图文
![使用Python中的OpenCV从图像中裁剪面](/upload/InfoBanner/zyjiaocheng/789/d60c28707f554124a6383f177f068a93.jpg)
我正在尝试从图像裁剪面部.
无论图像中有多少面,我都希望代码能够工作.
输入图像的示例:
Image with faces
我想裁剪面部,以便我可以对它们运行面部关键点检测算法(之前制作).
最终结果将如下所示:
Image after facial keypoint detection
我的代码目前是:
# Load in color image for face detection
image = cv2.imread('images/obamas4.jpg')
# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Make a copy of the original image to draw face detections on
image_copy = np.copy(image)
# Convert the image to gray
gray_image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
# Detect faces in the image using pre-trained face dectector
faces = face_cascade.detectMultiScale(gray_image, 1.25, 6)
# Print number of faces found
print('Number of faces detected:', len(faces))
# Get the bounding box for each detected face
for f in faces:
x, y, w, h = [ v for v in f ]
cv2.rectangle(image_copy, (x,y), (x+w, y+h), (255,0,0), 3)
# Define the region of interest in the image
face_crop = gray_image[y:y+h, x:x+w]
# Display the image with the bounding boxes
fig = plt.figure(figsize = (9,9))
axl = fig.add_subplot(111)
axl.set_xticks([])
axl.set_yticks([])
ax1.set_title("Obamas with Face Detection")
axl.imshow(image_copy)
# Display the face crops
fig = plt.figure(figsize = (9,9))
axl = fig.add_subplot(111)
axl.set_xticks([])
axl.set_yticks([])
axl.set_title("Obamas Face Crops")
axl.imshow(face_crop)
输出如下所示:
enter image description here
现在它只输出图像中检测到的最后一张脸.我确定我错过了像for循环一样简单的东西.
我希望能够在所有灰色裁剪的脸部图像上运行我的面部关键点检测算法.
谢谢您的帮助!
解决方法:
问题出在你的代码中,face_crop只存储检测到的最后一个面.
所以把它作为一个列表并附加所有面.然后使用for循环显示所有面.像这样:
face_crop = []
for f in faces:
x, y, w, h = [ v for v in f ]
cv2.rectangle(image_copy, (x,y), (x+w, y+h), (255,0,0), 3)
# Define the region of interest in the image
face_crop.append(gray_image[y:y+h, x:x+w])
for face in face_crop:
cv2.imshow('face',face)
cv2.waitKey(0)
我使用cv2.imshow()来显示图像.您可以修改它以使用plt.imshow()
希望这可以帮助!
内容总结
以上是互联网集市为您收集整理的使用Python中的OpenCV从图像中裁剪面全部内容,希望文章能够帮你解决使用Python中的OpenCV从图像中裁剪面所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。