matplotlib: ImportError: cannot import name 'pyplot' - python

I have matplotlib lib installed using pip but when I run this code it gives me this error:
shar#shar-Lenovo-G50-30 ~ $ python3 opencv.py
Traceback (most recent call last):
File "opencv.py", line 3, in <module>
from matplotlib import pyplot as plt
ImportError: cannot import name 'pyplot'
My code is:
import numpy as np
import cv2
from matplotlib import pyplot as plt
img1 = cv2.imread('/home/shar/home.jpg',0) # queryImage
img2 = cv2.imread('/home/shar/home2.jpg',0) # trainImage
# Initiate SIFT detector
orb = cv2.ORB()
# find the keypoints and descriptors with SIFT
kp1, des1 = orb.detectAndCompute(img1,None)
kp2, des2 = orb.detectAndCompute(img2,None)
# create BFMatcher object
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
# Match descriptors.
matches = bf.match(des1,des2)
# Sort them in the order of their distance.
matches = sorted(matches, key = lambda x:x.distance)
# Draw first 10 matches.
img3 = cv2.drawMatches(img1,kp1,img2,kp2,matches[:10], flags=2)
plt.imshow(img3),plt.show()
I also tried to install matplotlib from source and that still give me the error.

Make sure you don't have any file names matplotlib.py that you have created if any then rename or delete that file. It worked for me

Did you get error saying "cannot import name 'pyplot' from partially initialized module 'matplotlib' " ?
You could have unknowingly saved your file name as matplotlib.py, since it comes as default file name suggestion.
So change the file name and Bingo, you will not get that error again..

Related

AttributeError: module 'cv2' has no attribute 'face' OpenCV 4.7.0

After referring to some Stack Overflow answers I did pip install opencv-contrib-python, still I am getting those errors.
I am using OpenCV 4.7.0.
This is for a facial recognition project tutorial that I am following.
import cv2
import numpy as np
from PIL import Image
import os
# Path for face image database
path = 'dataset'
recognizer = cv2.face.LBPHFaceRecognizer_create()
detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml");
# function to get the images and label data
def getImagesAndLabels(path):
imagePaths = [os.path.join(path,f) for f in os.listdir(path)]
faceSamples=[]
ids = []
for imagePath in imagePaths:
PIL_img = Image.open(imagePath).convert('L') # grayscale
img_numpy = np.array(PIL_img,'uint8')
id = int(os.path.split(imagePath)[-1].split(".")[1])
faces = detector.detectMultiScale(img_numpy)
for (x,y,w,h) in faces:
faceSamples.append(img_numpy[y:y+h,x:x+w])
ids.append(id)
return faceSamples,ids
print ("\n [INFO] Training faces. It will take a few seconds. Wait ...")
faces,ids = getImagesAndLabels(path)
recognizer.train(faces, np.array(ids))
# Save the model into trainer/trainer.yml
recognizer.write('trainer/trainer.yml')
# Print the numer of faces trained and end program
print("\n [INFO] {0} faces trained. Exiting Program".format(len(np.unique(ids))))
I keep getting this error:
File "/Users/sashuponnaganti/workspace/Facial Recognition Project/face_trainer.py", line 7, in <module>
recognizer = cv2.face.LBPHFaceRecognizer_create()
AttributeError: module 'cv2' has no attribute 'face'
Any ideas how to fix this?
I already tried doing pip install opencv-contrib-python and I had already installed it so it made no difference.
This question has been solved. I had installed all my opencv packages in a conda environment but was running it with the wrong interpreter.

Cvlib not showing boxes, labels and confidence

I am trying to replicate a simple object detection that I found in on website.
import cv2
import matplotlib.pyplot as plt
import cvlib as cv
from cvlib.object_detection import draw_bbox
im = cv2.imread('downloads.jpeg')
bbox, label, conf = cv.detect_common_objects(im)
output_image = draw_bbox(im, bbox, label, conf)
plt.imshow(output_image)
plt.show()
All required libraries are installed and there are no errors running the code. However, it does not show the output image with the boxes, labels and confidence. How do I fix it?
#After loading an image use an assert:
img = cv2.imread('downloads.jpeg')
assert not isinstance(img,type(None)), 'image not found'

Getting the following error while using scikit-image to read images "AttributeError: 'PngImageFile' object has no attribute '_PngImageFile__frame' "

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

ImportError: cannot import name 'imshow'

unfortunalty I have not found a solution for this problem.
from imgutils import imshow
import cv2
img3 = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
plt.figure(figsize=(20,10))
plt.subplot(1,2,1); imshow(img)
plt.subplot(1,2,2); imshow(img3)
I get the following traceback:
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-31-8006396b3a04> in <module>
----> 1 from imgutils import imshow
2
3 img3 = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
4
5 plt.figure(figsize=(20,10))
ImportError: cannot import name 'imshow'
I am working on a Mac OS X 10.11, with a anaconda environment, python 3.5.
I have search the web to the imgutils module and have not a module, which have a imshow function.
Any suggestions?
Update
from cv2 import imshow
img3 = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
plt.figure(figsize=(20,10))
plt.subplot(1,2,1); imshow(img)
plt.subplot(1,2,2); imshow(img3)
Traceback
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-13-d01b4c235975> in <module>
5 plt.figure(figsize=(20,10))
6
----> 7 plt.subplot(1,2,1); imshow(img)
8 plt.subplot(1,2,2); imshow(img3)
TypeError: Required argument 'mat' (pos 2) not found
imgutils does not seem to contain an imshow attribute (and therefore definitely not a function). It does not contain an imshow submodule, nor does it imports an imshow function in the __init__.py file: it basically reimports elements from the submodules like, but a fast search does not yield an imshow function.
You probably wan to use the imshow from the matplotlib.pyplot module, so you should replace:
from imgutils import imshow
with:
from matplotlib.pyplot import imshow
This then imports the cv2.imshow [pyplot-doc] function.

shape_predictor in dlib module ArgumentError when using relative paths

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?

Categories

Resources