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!!
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?
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();
Related
I am trying to resolve captcha for the following image
!https://ibb.co/35X723J
I have tried using tessaract
data = br.open(captchaurl).read()
b = bytearray(data)
save = open(filename, 'wb')
save.write(data)
save.close()
ctext= pytesseract.image_to_string(Image.open(filename))
Here is a workaround. You need to clear a bit the image but you wont get a perfect result. Try the following:
try:
from PIL import Image
except ImportError:
import Image
import pytesseract
import cv2
file = 'sample.jpg'
img = cv2.imread(file, cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img, None, fx=10, fy=10, interpolation=cv2.INTER_LINEAR)
img = cv2.medianBlur(img, 9)
th, img = cv2.threshold(img, 185, 255, cv2.THRESH_BINARY)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (4,8))
img = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
cv2.imwrite("sample2.jpg", img)
file = 'sample2.jpg'
text = pytesseract.image_to_string(file)
print(''.join(x for x in text if x.isdigit()))
Option 1:
I think using Pytesseract should solve the issue. I tried out your code and it gave me the following result when i gave in the exact cropped captcha image as input into pytesseract:
Input Image:
Output:
print(ctext)
'436359 oS'
I suggest you don't give the full page url as input into pytesseract. Instead give the exact image url as "https://i.ibb.co/RGn9fF5/Jpeg-Image-CS2.jpg" which will take in only the image.
And regarding the extra 'oS' characters in the output, you can do a string manipulation to chop off the characters other than numbers in the output.
re.sub("[^0-9]", "", ctext)
Option 2:
You can also use google's OCR to accomplish this which gives you the exact result without errors. Though I have shown you the web interface of it, google has nice python libraries through which you can accomplish this using python itself. Looks like this:
I am writing this simple code but this is showing error saying size.width>0&&size.height>0 in function imshow()enter code here
import numpy as np
import cv2
img = cv2.imread('C:/Users/Desktop/x.jpg',0)
cv2.namedWindow('image',cv2.WINDOW_NORMAL)
cv2.imshow('image',img)
cv2.namedWindow('image',cv2.WINDOW_NORMAL)
cv2.waitKey(0)
cv2.destroyAllWindows()
Assuming you are using Windows, write path name as:
img = cv2.imread('C:\\Users\\Desktop\\x.jpg', 0)
to load the image correctly.
I want to do a practice that consists of capturing webs in jpg, but it did not just work (I am newbie), this is the code I use.
import numpy as np
import urllib
import cv2
def url_to_image("http://www.hereiputweb.com"):
resp = urllib.urlopen("http://www.hereiputweb.com")
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
return image
The code I got it from a manual but it gives me fault in the line:
def url_to_image("http://www.hereiputweb.com"):
I think I indicated the web incorrectly, very far I should not be .. tried several forms but nothing .. what do I do wrong?
regards
There is a really brief tutorial (https://docs.python.org/3/tutorial/).
The relevant part would be https://docs.python.org/3/tutorial/controlflow.html#defining-functions
So, you should define your function as follows:
def url_to_image(url):
resp = urllib.urlopen(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
return image
I have not checked the implementation works ;)
Then you can use your function:
url = "http://www.hereiputweb.com"
my_image = url_to_image(url)
The problem is not with your implementation, it's with your URL!
This method require a functioning URL that returns an image. The URL you're using is not an image.
Try using an URL of an image (e.g: some URLs that end with .jpg) and it shall work!
Remember that the URL must be on-line!
I have come across this link for face detection and image cropping. I would like to use this script but I have cv2 install and only import cv2 works but not import cv.
How can I convert the cv functions in the following function to cv2 functions?
def faces_from_pil_image(pil_image):
"Return a list of (x,y,h,w) tuples for faces detected in the PIL image"
storage = cv.CreateMemStorage(0)
facial_features = cv.Load('haarcascade_frontalface_alt.xml', storage=storage)
cv_im = cv.CreateImageHeader(pil_image.size, cv.IPL_DEPTH_8U, 3)
cv.SetData(cv_im, pil_image.tostring())
faces = cv.HaarDetectObjects(cv_im, facial_features, storage)
# faces includes a `neighbors` field that we aren't going to use here
return [f[0] for f in faces]
Either use
import cv2
storage = cv2.cv.CreateMemStorage(0)
or
from cv2 import *
storage = cv.CreateMemStorage(0)
I'm new to python and open cv. I'm trying to find out how to load an image in opencv with python. Can any one provide an example (with code) explaining how to load the image and display it?
import sys
import cv
from opencv.cv import *
from opencv.highgui import *
ll="/home/pavan/Desktop/iff pics/out0291.tif"
img= cvLoadImage( ll );
cvNamedWindow( “Example1”, CV_WINDOW_AUTOSIZE );
cvShowImage( “Example1”, img );
cvWaitKey(10);
cvDestroyWindow( “Example");
There have been quite a few changes in the openCV2 API:
import cv
ll = "/home/pavan/Desktop/iff pics/out0291.tif"
img = cv.LoadImage(ll)
cv.NamedWindow("Example", cv.CV_WINDOW_AUTOSIZE )
cv.ShowImage("Example", img )
cv.WaitKey(10000)
cv.DestroyWindow("Example")
It is a simpler, quite cleaner syntax!
Also, you don't need trailing ; à-la-matlab. Last, be careful about the quotes you use.
For the newer openCV3 API, you should see the other answer to this question.
import cv2
image_path = "/home/jay/Desktop/earth.jpg"
img = cv2.imread(image_path) # For Reading The Image
cv2.imshow('image', img) # For Showing The Image in a window with first parameter as it's title
cv2.waitKey(0) #waits for a key to be pressed on a window
cv2.destroyAllWindows() # destroys the window when the key is pressed
There are 2 possible approaches to this:
Using argparse (recommended):
import cv2
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required = True,help = "Path to the image")
args = vars(ap.parse_args())
image = cv2.imread(args["image"])
This will take the image as an argument, will then convert the argument, add it to ap and the load it using the imread function()
To run it.
Go to your required folder
source activate your environment
python filename.py -i img.jpg
Hardcoding the image location:
import cv2
img = cv2.imread("\File\Loca\img.jpg")
cv2.imshow("ImageName",img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Run this similarly, omitting the arguments.