简体   繁体   中英

opencv python face detection from url images

I have no problem getting the opencv face detection using haar feature based cascades working on saved images:

from PIL import Image
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')

img = cv2.imread('pic.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(gray, 1.3, 5)

but I can't figure out how to open a url image and pass it into face_cascade. I've been playing around with cStringIO, but I don't know what to do with it...

import cv2.cv as cv
import urllib, cStringIO
img = 'http://scontent-b.cdninstagram.com/hphotos-prn/t51.2885-15/10424498_582114441904402_1105042543_n.png'
file = cStringIO.StringIO(urllib.urlopen(img).read())
source = Image.open(file).convert("RGB")
bitmap = cv.CreateImageHeader(source.size, cv.IPL_DEPTH_8U, 3)
cv.SetData(bitmap, source.tostring())
cv.CvtColor(bitmap, bitmap, cv.CV_RGB2BGR)

is it possible to work with a numpy array instead?

source2 = Image.open(file)
imarr=numpy.array(source2,dtype=numpy.uint8)

I'm a beginner, so I apologize for the poor explanation. thanks a lot in advance!!

Or in another way you can use VideoCapture() class to open url image.

See the C++ code below,

VideoCapture cap;

if(!cap.open("http://docs.opencv.org/trunk/_downloads/opencv-logo.png")){
cout<<"Cannot open image"<<endl;
return -1;
}
Mat src;
cap>>src;
imshow("src",src);
waitKey();

In your first example you are using OpenCV2.imread to read your image in the second you are presumably using PIL.Image then trying to convert.

Why not simply save the file to a temp directory and then use OpenCV2.imread again?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM