【问题标题】:how to crop the detected face in opencv and save roi as image in opencv python如何在opencv中裁剪检测到的人脸并将roi保存为opencv python中的图像
【发布时间】:2014-05-11 14:53:08
【问题描述】:

我在 python 中使用 opencv,这是我检测面部和保存面部的代码..但它不保存 roi(检测到的面部),我在执行此操作时遇到了麻烦。请帮助我如何解决这个问题。

   TRAINSET = "data/lbpcascades/lbpcascade_frontalface.xml"
   DOWNSCALE = 4

   cam = cv2.VideoCapture(0) #capture a video

   cv2.namedWindow("preview")
   classifier = cv2.CascadeClassifier(TRAINSET) 

   Compare_images=[]
   for file in os.listdir("images"):
       if file.endswith(".jpg"):
          Compare_images.append(file)
while True: # try to get the first frame
    _, frame = cam.read() 

key = cv2.waitKey(20)
if(key==32):

    print "Name of Image:"

    n= raw_input()

    value=len(Compare_images)
    cv2.imwrite('images/image'+str(n)+'.jpg', frame)
    saved_image=cv2.imread("images/image"+str(n)+".jpg")
    minisize = (saved_image.shape[1]/DOWNSCALE,saved_image.shape[0]/DOWNSCALE)
    miniframe = cv2.resize(saved_image, minisize)
    faces = classifier.detectMultiScale(miniframe)
    for f in faces:
        x, y, w, h = [ v*DOWNSCALE for v in f ]     
        print x 
        print y,w,h      

        x0,y0=int(x),int(y)
        x1,y1=int(x+w),int(y+h)
        print x0,y0,y1,y0

        image = cv2.rectangle(saved_image, (x0,y0), (x1,y1), (0,0,255),2)

        roi=saved_image[y0:y1,x1:x0]#crop 
        cv2.imwrite('roi.jpg',roi)
        cv2.imshow("adsa", saved_image) 


cv2.putText(frame, "Press ESC to close.", (5, 25),
            cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255,255,255))
cv2.imshow("preview", frame)

【问题讨论】:

标签: python opencv image-processing


【解决方案1】:

你的意思是?:

.
.
.
print x0,y0,x1,y1
.
.
.
roi=saved_image[y0:y1,x0:x1]

while 语句上方和下方的缩进似乎不正确。

三引号只能临时用于块引号,因为它们可能会导致问题。

也许改用#

#x0,y0=x,y
#x1,y1=x+w,y+h

除非该函数的帮助应该是这样阅读的。

在您的问题中包含错误也会有所帮助。

【讨论】:

  • 代码有效。没有错误,但我使用 roi 保存的图像(检测到的面部)是空的......我希望你能帮助我。 roi=saved_image[y0:y1,x0:x1] 这是我裁剪图像的部分,所以我只能保存人脸
  • @user2356747 我不知道图像是空的,或者代码工作正常。问题中没有提到这一点。对不起。当您使用建议的更改运行代码时会发生什么? (例如saved_image[y0:y1,x0:x1],而不是你给saved_image[y0:y1,x1:x0]的代码中的内容)图像仍然是空的吗?
  • 抱歉没有提及。我会尝试你的建议。
猜你喜欢
  • 2016-01-01
  • 2015-03-29
  • 2012-03-08
  • 2013-01-23
  • 2019-06-11
  • 2018-07-08
  • 2017-02-21
  • 1970-01-01
  • 2019-11-25
相关资源
最近更新 更多