I have come across a strange error when using dlib.shape_predictor function.
This is my code:
import sys
import dlib
from skimage import io
import matplotlib.pyplot as plt
import os
predictor_model = os.path.join(os.path.dirname(__file__),"Models","shape_predictor_68_face_landmarks.dat")
# Take the image file name from the command line
file_name = "/home/matt/Programming/Python/Face_detection/Images/wedding_photo.jpg"
# Test if they are equivalent
print predictor_model == "/home/matt/Programming/Python/Face_detection/Models/shape_predictor_68_face_landmarks.dat"
predictor_model = "/home/matt/Programming/Python/Face_detection/Models/shape_predictor_68_face_landmarks.dat"
# Create a HOG face detector using the built-in dlib class
face_detector = dlib.get_frontal_face_detector()
face_pose_predictor = dlib.shape_predictor(predictor_model)
If I use the predictor model as defined through relative path using os then I get an error:
ArgumentError: Python argument types in
shape_predictor.__init__(shape_predictor, unicode)
did not match C++ signature:
__init__(boost::python::api::object, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)
__init__(_object*)
If I hardcode the path as defined above the script runs without a problem. Any ideas what may have gone wrong?
Related
While using the rpy2 library of Python to work with R. I get the following error message while trying to import a function of the bnlearn package:
# Using R inside python
import rpy2
import rpy2.robjects as robjects
import rpy2.robjects.packages as rpackages
from rpy2.robjects.vectors import StrVector
from rpy2.robjects.packages import importr
utils = rpackages.importr('utils')
utils.chooseCRANmirror(ind=1)
# Install packages
packnames = ('visNetwork', 'bnlearn')
utils.install_packages(StrVector(packnames))
# Load packages
visNetwork = importr('visNetwork')
bnlearn = importr('bnlearn')
tabu = bnlearn.tabu
fit = bn.learn.bn.fit
With the error:
AttributeError: module 'bnlearn' has no attribute 'bn'
While checking the bnlearn documentation one finds out that bn is a class structure. So one should check out all the attributes of the object in question, that is, running:
bnlearn.__dict__['_rpy2r']
After that you should get a similar output like the next one, where you find how you would import each attribute of bnlearn:
...
...
'bn_boot': 'bn.boot',
'bn_cv': 'bn.cv',
'bn_cv_algorithm': 'bn.cv.algorithm',
'bn_cv_structure': 'bn.cv.structure',
'bn_fit': 'bn.fit',
'bn_fit_backend': 'bn.fit.backend',
'bn_fit_backend_continuous': 'bn.fit.backend.continuous',
'bn_fit_backend_discrete': 'bn.fit.backend.discrete',
'bn_fit_backend_mixedcg': 'bn.fit.backend.mixedcg',
'bn_fit_barchart': 'bn.fit.barchart',
'bn_fit_dotplot': 'bn.fit.dotplot',
...
...
Then, running the following will solve the issue:
bn_fit = bnlearn.bn_fit
Now, you could, for example, run a bayesian Network:
structure = tabu(datos, score = "loglik-g")
bn_mod = bn_fit(structure, data = datos, method = "mle")
In general, this approach solves the issue of importing any function from an R package into Python through the rpy2 package.
I am receving this error while I am try to run the code (from CMD):
ModuleNotFoundError: No module named 'numbers.hog'; numbers is not a package
Here is the hog.py file code...
from skimage import feature
class HOG:
def __init__(self, orientations = 9, pixelsPerCell = (8, 8),
cellsPerBlock = (3, 3), normalize = False):
self.orienations = orientations
self.pixelsPerCell = pixelsPerCell
self.cellsPerBlock = cellsPerBlock
self.normalize = normalize
def describe(self, image):
hist = feature.hog(image,
orientations = self.orienations,
pixels_per_cell = self.pixelsPerCell,
cells_per_block = self.cellsPerBlock,
normalize = self.normalize)
return hist
...and the main (train.py) which return the error.
from sklearn.svm import LinearSVC
from numbers.hog import HOG
from numbers import dataset
import argparse
import pickle as cPickle
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", required = True,
help = "path to the dataset file")
ap.add_argument("-m", "--model", required = True,
help = "path to where the model will be stored")
args = vars(ap.parse_args())
(digits, target) = dataset.load_digits(args["dataset"])
data = []
hog = HOG(orientations = 18, pixelsPerCell = (10, 10),
cellsPerBlock = (1, 1), normalize = True)
for image in digits:
image = dataset.deskew(image, 20)
image = dataset.center_extent(image, (20, 20))
hist = hog.describe(image)
data.append(hist)
model = LinearSVC(random_state = 42)
model.fit(data, target)
f = open(args["model"], "w")
f.write(cPickle.dumps(model))
f.close()
I don't uderstand why it gives me error on module package. numbers is a package, why it don't import it as well (as it seems) ?
UPDATE: tried to put from .hog import HOG and then execute from CMD..It prints:
No module named '__main__.hog'; '__main__' is not a package
Is it crazy ? hog.py is in the main package together with the other files. As you can see, it also contains HOG class.... Can't understand.. Some one can reproduce the error ?
In the IDE console it prints:
usage: train.py [-h] -d DATASET -m MODEL
train.py: error: the following arguments are required: -d/--dataset, -m/--model
This should be correct as soon as it is executed in IDE because the program MUST run in CMD.
UPDATE 2: for who is interested, this is the project https://github.com/VAUTPL/Number_Detection
Change from numbers.hog import HOG to from hog import HOG and change from numbers import dataset to import dataset.
You are already in the "numbers" package so you don't have to precise it again when you import it.
When you type from numbers import dataset, Python will look for a package numbers (inside the actual package) that contains a dataset.py file.
If your train.py was outside the numbers package then you have to put the package name (numbers) before.
Important
numbers is a python standard package
https://docs.python.org/2/library/numbers.html
Check if you are not really importing that package or rename your package to a more specific name.
Also:
It might looks like python doesnt recognize your package.
Open a python shell and write:
import sys
print sys.path
Check if your number path is there.
If it's not there you have to add it.
sys.path.insert(0, "/path/to/your/package_or_module")
Your train.py file is already in the package "numbers", so you don't have to import numbers.
Try this instead:
from hog import HOG
I saw in comment that it gives you "error (red line)".
Can you be more precise, because I don't see errors there.
I am using a Windows 10 machine and have installed Python, numpy and OpenCV from the official link using pre built binaries. I can successfully import numpy and cv2 but get an error when I try to import cv.
import cv2
import numpy as np
import sys
import cv
def diceroll():
rng = cv.RNG(np.random.randint(1,10000))
print 'The outcome of the roll is:'
print int(6*cv.RandReal(rng) + 1)
return
diceroll()
ImportError: No module named cv
P.S: This is not a possible duplicate of this question. The user in the question involved is getting a dll file error whereas I am stuck with an import error for cv.
After inquiring on the OpenCV community, I learnt that the old cv or cv2.cv api was removed entirely from OpenCV3
One cannot use the RNG function from cv through opencv3. You can instead use numpy.random for the same functionality.
Reference: my question on Opencv community
It is somewhere in there, just need to search for it. Try running something like the following on your system:
from types import ModuleType
def search_submodules(module, identifier):
assert isinstance(module, ModuleType)
ret = None
for attr in dir(module):
if attr == identifier:
ret = '.'.join((module.__name__, attr))
break
else:
submodule = getattr(module, attr)
if isinstance(submodule, ModuleType):
ret = search_submodules(submodule, identifier)
return ret
if __name__ == '__main__':
import cv2
print cv2.__version__
print search_submodules(cv2, 'RNG')
On my system, this prints:
2.4.11
cv2.cv.RNG
I am trying to run following python code from c++(embedding python).
import sys
import os
import time
import win32com.client
from com.dtmilano.android.viewclient import ViewClient
import re
import pythoncom
import thread
os.popen('adb devices')
CANalyzer = None
measurement = None
def can_start(config_path):
global CANalyzer,measurement
CANalyzer = win32com.client.Dispatch('CANalyzer.Application')
CANalyzer.Visible = 1
measurement = CANalyzer.Measurement
CANalyzer.Open(config_path)
measurement.Start()
com_marshall_stream = pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch,CANalyzer)
return com_marshall_stream
When i try to call can_start function, i am getting python type error . Error traceback is mentioned below.
"type 'exceptions.TypeError'. an integer is required. traceback object at 0x039A198"
The function is executing if i directly ran it from the python and also it is executing in my pc, where the code was developed. But later when i transferred to another laptop, i am experiencing this problem.
I have a simple code as mentioned below:
import cv
from opencv.cv import *
from opencv.highgui import *
img = cv.LoadImage("test.jpg")
cap = cv.CreateCameraCapture(0)
while cv.WaitKey(1) != 10:
img = cv.QueryFrame(cap)
cv.ShowImage("cam view", img)
cascade = cv.LoadHaarClassifierCascade('haarcascade_frontalface_alt.xml', cv.Size(1,1))
But I faced to this error:
# AttributeError: 'module' object has no attribute 'LoadImage'
when I change the code to below:
import cv
#from opencv.cv import *
#from opencv.highgui import *
img = cv.LoadImage("test.jpg")
cap = cv.CreateCameraCapture(0)
while cv.WaitKey(1) != 10:
img = cv.QueryFrame(cap)
cv.ShowImage("cam view", img)
cascade = cv.LoadHaarClassifierCascade('haarcascade_frontalface_alt.xml', cv.Size(1,1))
now the first error got solve and another error raise.
AttributeError: 'module' object has no attribute 'LoadHaarClassifierCascade'
I need both of the modules but it seems that they have conflict to gether.
Now what I have to do?
In OpenCV to load a haar classifier (in the python interface anyway) you just use cv.Load.
import cv
cascade = cv.Load('haarcascade_frontalface_alt.xml')
See the examples here.
Also, the samples that come with the OpenCV source are really good (in OpenCV-2.xx/samples/python).
How do you access the stuff you've imported?
# imports the cv module, all stuff contained in it and
# the module itself is now accessible via: cv.classname, cv.functionname
# where classname, functionname is the name of the class/function which
# the cv module provides..
import cv
# imports everything contained in the opencv.cv module
# after this import it is available via it's classname, functionname, etc.
# Attention: without prefix!!
from opencv.cv import *
# #see opencv.cv import
from opencv.highgui import *
#see python modules for more details about modules and imports in python.
If you can provide which classes are contained in which module I could add a specific solution for your problem.