3
\$\begingroup\$

Is there a better way to rewrite this part in python. It doesnot have to be shorter as long as its much better. thanks in advance

count = 1
while count < 10:
 _, pho = webcam.read()
 gr = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
 images = face_cascade.detectMultiScale(gr, 1.3, 4)
 for (x,y,w,h) in faces: 
 cv2.rectangle(pho,(x,y),(x+w,y+h),(0,255,0),2)
 fa = gray[y:y + h, x:x + w]
 e_size = cv2.resize(fa, (100, 100))
 cv2.imwrite('%s/%s.JPEG' % (folder,count), e_size)
 count += 1
 cv2.imshow('OpenCV', pho)
 key = cv2.waitKey(20) 
asked Sep 1, 2017 at 13:47
\$\endgroup\$
0

1 Answer 1

2
\$\begingroup\$

A very simple change that replaces the while loop with a for loop (I don't know much about OpenCV, so I can't help too much there):

for count in range(1, 10):
 _, pho = webcam.read()
 gr = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
 images = face_cascade.detectMultiScale(gr, 1.3, 4)
 for (x,y,w,h) in faces: 
 cv2.rectangle(pho,(x,y),(x+w,y+h),(0,255,0),2)
 fa = gray[y:y + h, x:x + w]
 e_size = cv2.resize(fa, (100, 100))
 cv2.imwrite('%s/%s.JPEG' % (folder,count), e_size)
 cv2.imshow('OpenCV', pho)
 key = cv2.waitKey(20) 

Additionally, in Python 3 especially, the % string formatting syntax is out-of-favor/deprecated -- use the {} and .format syntax instead:

cv2.imwrite('%s/%s.JPEG' % (folder,count), e_size)

becomes

cv2.imwrite('{!s}/{!s}.JPEG'.format(folder, count), e_size)
answered Sep 1, 2017 at 14:53
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.