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.
Related
I am using scikit-image to load a random image from a folder. OpenCV is being used for operations later on..
Code is as follows (only relevant parts included)
import imageio
import cv2 as cv
import fileinput
from collections import Counter
from data.apple_dataset import AppleDataset
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
from torchvision.models.detection.mask_rcnn import MaskRCNNPredictor
from torchvision.transforms import functional as F
import utility.utils as utils
import utility.transforms as T
from PIL import Image
import skimage.io
from skimage.viewer import ImageViewer
from matplotlib import pyplot as plt
%matplotlib inline
APPLE_IMAGE_PATH = r"__mypath__\samples\apples\images"
# Load a random image from the images folder
FILE_NAMES = next(os.walk(APPLE_IMAGE_PATH))[2]
random_apple_in_folder = os.path.join(APPLE_IMAGE_PATH, random.choice(FILE_NAMES))
apple_image = skimage.io.imread(random_apple_in_folder)
apple_image_cv = cv.imread(random_apple_in_folder)
apple_image_cv = cv.cvtColor(apple_image_cv, cv.COLOR_BGR2RGB)
Error is as follows
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-3-9575eed18f18> in <module>
11 FILE_NAMES = next(os.walk(APPLE_IMAGE_PATH))[2]
12 random_apple_in_folder = os.path.join(APPLE_IMAGE_PATH, random.choice(FILE_NAMES))
---> 13 apple_image = skimage.io.imread(random_apple_in_folder)
14 apple_image_cv = cv.imread(random_apple_in_folder)
AttributeError: 'PngImageFile' object has no attribute '_PngImageFile__frame'
How do i proceed from here? What should i change???
This is a bug in Pillow 7.1.0. You can upgrade Pillow with pip install -U pillow. See this bug report for more information:
https://github.com/scikit-image/scikit-image/issues/4548
I would like to ask for help to modify/edit the mesh of a Part Instance (under Assembly).
I have tried (code below), but it is not possible because of the tuple:
mdb.models[modelName].rootAssembly.instances[instanceName].nodes[i].coordinates[0] = newCoordXYZ[0] # for x
mdb.models[modelName].rootAssembly.instances[instanceName].nodes[i].coordinates[1] = newCoordXYZ[1] # for y
mdb.models[modelName].rootAssembly.instances[instanceName].nodes[i].coordinates[2] = newCoordXYZ[2] # for z
TypeError: 'tuple' object does not support item assignment
Or, if possible, to directly add/assign the mesh (which is already stored in a variable - newCoordXYZ) to the geometry in the Assembly module!?
Any idea/suggestion is more than welcomed!
PS: I know that the modification of the mesh can be easily done in the Part Module (mesh dependent) with the editNode() command.
partName = mdb.models[modelName].parts[partName]
partName.editNode(nodes=partName.nodes,coordinates=newCoordXYZ)
EDIT 01:
comment
I'm not sure, I might make so trivial mistake.
I still obtain the following error: AttributeError: 'PartInstance' object has no attribute 'editNode', which is in agreement with the documentation:
The documentation says:
Abaqus > Scripting Reference > Python commands > Assembly commands > Assembly object:
Access
import assembly
mdb.models[name].rootAssembly
Abaqus > Scripting Reference > Python commands > Assembly commands > PartInstance object:
Access
import assembly
mdb.models[name].rootAssembly.allinstances
mdb.models[name].rootAssembly.instances[name]
and
Abaqus > Scripting Reference > Python commands > Edit mesh commands > Assembly object: editNode(...)
This method changes the coordinates of the given nodes on a part instance.
Abaqus > Scripting Reference > Python commands > Edit mesh commands > Part object
has no editNode(...) cmd
So, by using this cmd: mdb.models[name].rootAssembly.instances[name] I cannot use editNode()...
py code
################################## LIBRARY #############################
from datetime import date
from part import *
from material import *
from section import *
from assembly import *
from step import *
from interaction import *
from load import *
from mesh import *
from optimization import *
from job import *
from sketch import *
from visualization import *
from connectorBehavior import *
import regionToolset
import assembly
import visualization
import os
import datetime
import shutil
from odbAccess import *
import time
import numpy
import numpy as np
import re
import meshEdit
############### Add textFileName with new coord (+ imp )######################
fileNameImp = open("out_newCoordX_Imp.txt","r")
impVect = fileNameImp.readlines()
fileNameImp.close()
####################### Add modelName and instanceName #######################
modelName = 'Model-1'
instanceName = 'Part-1-1'
assemblyInstance = mdb.models[modelName].rootAssembly.instances[instanceName]
newCoordXYZ = numpy.zeros((len(assemblyInstance.nodes),3))
for i in assemblyInstance.nodes:
newCoordXYZ[i.label-1][0] = float(impVect[i.label-1])
newCoordXYZ[i.label-1][1] = i.coordinates[1]
newCoordXYZ[i.label-1][2] = i.coordinates[2]
assemblyInstance.editNode(nodes=assemblyInstance.nodes,coordinates=newCoordXYZ)
The same way you do it for the part, you should do it for assembly instance:
assemblyInstance = mdb.models[modelName].rootAssembly.instances[instanceName]
assemblyInstance.editNode(nodes=assemblyInstance.nodes,coordinates=newCoordXYZ)
Make sure to make your instance independent!
This is my code.
import sys, os
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from scipy import *
sys.path.insert(0, 'C:/research')
im = Image.open('C:/research/1.jpg')
hei, wei = im.height, im.width
im_bicubic = im.resize((wei,hei), im.BICUBIC)
im.save('C:/research/1ori.jpg') #original image
im_bicubic.save('C:/research/1bic.jpg') #Images with bicubic applied
But I get this error.
AttributeError: 'JpegImageFile' object has no attribute 'BICUBIC'
Why is this message coming up?
.bmp, the same message pops up.
What should I do?
You need to use PIL.Image.BICUBIC instead of im.BICUBIC.
So you need to change:
im_bicubic = im.resize((wei,hei), im.BICUBIC)
to
im.resize((wei,hei),PIL.Image.BICUBIC)
You also need to import pil like so:
import PIL
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?
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