Python cv2 MSER not working - python

I have installed cv2 (opencv-3.0.0) on my Windows machine, but unable to access MSER class:
import cv2
cv2.MSER()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'MSER'
For cv2 installation, I downloaded and extracted opencv-3.0.0.0.exe and then copied cv2.pyd to Ananconda sitepackage directory.
I see couple of post on internet about using cv2.MSER, but I can't figure out what is the issue with my cv2.

I was refering opencv-2.4 way of using MSER. From opencv-3.0.0 documentation, it appears that I need to use following:
cv2.MSER_create()

cam = video.create_capture(video_src)
mser = cv2.MSER_create()
while True:
ret, img = cam.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
vis = img.copy()
regions = mser.detectRegions(gray, None)

Related

How to get set of colours in an processed image using python PIL

I have an image and when I process it, I can´t get the colors.
Here is my code:
import cv2
from PIL import Image
im = Image.open ('imag.jpg')
ret,thresh1 = cv2.threshold(im,127,255,cv2.THRESH_BINARY)
from collections import defaultdict
by_color = defaultdict(int)
for pixel in thresh1.getdata():
by_color[pixel] += 1
print (by_color)
If I run just the original image (im), works well. But when I run processed image (thresh1), the following error appears:
Traceback (most recent call last):
File "file.py", line 62, in <module>
ret,thresh1 = cv2.threshold(im,127,255,cv2.THRESH_BINARY)
TypeError: Expected cv::UMat for argument 'src'
For this function:
ret,thresh1 = cv2.threshold(im,127,255,cv2.THRESH_BINARY)
to work you should read image using cv2.imread (returns numpy.array) rather than PIL.Image.open (returns Image object).

Python face detection not working in terminal

I am trying to make a face detection python programme using opencv but when i run the following shell command I get the following error:
when i typed: python main2.py abba.png haarcascade_frontalface_default.xml
I am using opencv and I used the following documentationRealpython face Recognition:
(venv) C:\Users\User\PycharmProjects\main_1>python face_detect.py abba.png haarcascade_frontalface_default.xml
C:\Users\User\AppData\Local\Programs\Python\Python39\python.exe: can't open file 'C:\Users\User\PycharmProjects\main_1\face_detect.py': [Errno 2] No such file or directory
(venv) C:\Users\User\PycharmProjects\main_1>python main2.py abba.png haarcascade_frontalface_default.xml
Traceback (most recent call last):
File "C:\Users\User\PycharmProjects\main_1\main2.py", line 13, in <module>
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-95hbg2jt\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src
.empty() in function 'cv::cvtColor'
Here is the Code I used:
import sys
import cv2
# Get user supplied values
imagePath = sys.argv[1]
cascPath = sys.argv[2]
# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)
# Read the image
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Detect faces in the image
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.cv.CV_HAAR_SCALE_IMAGE
)
print("Found {0} faces!".format(len(faces)))
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imshow("Faces found", image)
cv2.waitKey(0)
This error indicates that the image file wasn't found correctly:
C:\Users\User\AppData\Local\Programs\Python\Python39\python.exe: can't open file 'C:\Users\User\PycharmProjects\main_1\face_detect.py': [Errno 2] No such file or directory
And thus it can't convert color using opencv of something (image) that's not a valid file.
File "C:\Users\User\PycharmProjects\main_1\main2.py", line 13, in <module>
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-95hbg2jt\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src
.empty() in function 'cv::cvtColor'
So, check if your folder contains the file you want to use, in your case: abba.png.
Use the command dir to list all the directories and files in a directory using windows cmd; ls is a unix command.
You can apply face detection within deepface. It wraps several face detectors. Here, mtcnn is the most robust but the slowest one. ssd is the fastest. The framework will download required dependencies in the background.
#!pip install deepface
from deepface import DeepFace
detectors = ['opencv', 'ssd', 'mtcnn', 'dlib']
img = DeepFace.detectFace("img.jpg", detector_backend = detectors[0])

python failed to run script but successfully run line by line

when i run the code using Ipython3 it works.
but when I try to run it a python script via the terminal and getting the next error:
Traceback (most recent call last):
File "procces_image.py", line 3, in <module>
import mahotas as mh
File "/home/s/.local/lib/python3.6/site-packages/mahotas/__init__.py", line 83, in <module>
from . import polygon
File "/home/s/.local/lib/python3.6/site-packages/mahotas/polygon.py", line 8, in <module>
from . import _convex
ValueError: module functions cannot set METH_CLASS or METH_STATIC
import cv2
import pylab
import mahotas as mh
import matplotlib.pyplot as plt
from PIL import Image
path = '2_1.tif'
image = mh.imread(path)
im = Image.open(path)
img = Image.new('P', (1024, 1024))
img.paste(im)
pylab.imshow(img)
pylab.show()
print(image.shape)
im = mh.gaussian_filter(im, 4)
im = im.astype('uint8')
ret,thresh = cv2.threshold(im,130,255,0)
T = mh.thresholding.otsu(im)
labeled,nr_objects = mh.label(im > T)
labeled = labeled.astype('uint8')
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
pylab.imshow(im)
pylab.show()
im1 = Image.open(path)
im1.paste(im)
pylab.show()
the computer was recently formatted.
And all the packages are updated.
the code was originally created in Visual Studio code.
for some reason the matplotlib didn't work well with the mahotas
I neened to reinstall matplotlib using
sudo -H apt-get install python3-matplotlib

Inserting icc color profile into image using Pillow ImageCMS

I am trying to insert an ICC color profile into an image. Using code from this post as an example my code looks like this:
from PIL import Image, ImageCms
# Read image
img = Image.open(IMG_PATH)
# Read profile
profile = ImageCms.getOpenProfile(PROFILE_PATH)
# Save image with profile
img.save(OUT_IMG_PATH, icc_profile=profile)
I get the following error
Traceback (most recent call last):
File "/home/----/Documents/code_projects/hfss-misc/icc_profiles/insert_icc_profile_into_image.py", line 17, in <module>
img.save(OUT_IMG_PATH, icc_profile=srgb_profile)
File "/home/----/.virtualenvs/color-correction/lib/python3.6/site-packages/PIL/Image.py", line 2102, in save
save_handler(self, fp, filename)
File "/home/----/.virtualenvs/color-correction/lib/python3.6/site-packages/PIL/JpegImagePlugin.py", line 706, in _save
markers.append(icc_profile[:MAX_DATA_BYTES_IN_MARKER])
TypeError: 'PIL._imagingcms.CmsProfile' object is not subscriptable
I thought that there might be a problem with my ICC profile so I tried to use one generated by Pillow.
from PIL import Image, ImageCms
# Read image
img = Image.open(IMG_PATH)
# Creating sRGB profile
profile = ImageCms.createProfile("sRGB")
# Save image with profile
img.save(OUT_IMG_PATH, icc_profile=profile)
I still get the same error, however.
Does anyone know what the cause for this error is?
My system environment is as follows:
Ubuntu 18.04
Python 3.6
Pillow==7.0.0
The answer from github at (https://github.com/python-pillow/Pillow/issues/4464) was to use profile.to_bytes():
img.save(OUT_IMG_PATH, icc_profile=profile.tobytes())

RuntimeError using cv.SaveImage in openCV

I want to convert a jpg file to png, but when I run this code :
from opencv import _cv
from opencv.highgui import cvSaveImage, cvLoadImage
cvSaveImage("bet.jpg",cvLoadImage("bet.jpg"))
if __name__ == '__main__':
pass
It gives this error which I don't understand :
Traceback (most recent call last):
File "convert.py", line 6, in <module>
cvSaveImage("bet.jpg",cvLoadImage("bet.jpg"))
File "/usr/lib/pymodules/python2.6/opencv/highgui.py", line 183, in cvSaveImage
return _highgui.cvSaveImage(*args)
RuntimeError: openCV Error:
Status=Null pointer
function name=cvGetMat
error message=NULL array pointer is passed
file_name=cxarray.cpp
line=2780
I have my picture with the same folder of source code and the name of the image is bet.jpg
Any idea ??
The best choice is pyopencv:
import pyopencv as cv
img = cv.imread('01.png')
cv.imshow('img-windows',img)
cv.waitKey(0)
cv.imwrite('01.png',img)
From Python CV documentation, the CV2 method for converting a jpeg to png is:
Python: cv2.imwrite(filename, img[, params]) → retval
For my example:
import cv2
filename = 'pic.jpeg'
cam = cv2.VideoCapture(filename)
s, img = cam.read()
picName = 'pic.png'
cv2.imwrite(picName, img)
VideoCapture is nice and general, and works with videos, webcams and image files.
I solved the problem, the image I took randomly from the Google Images doesn't load. Maybe it's encrypted or something I don't know. I tried it with other images, and worked very well. So watch out while copying images : )

Categories

Resources