How to use "xphoto_WhiteBalancer.balanceWhite" with Python and OpenCV? - python

I am looking for a straightforward way of applying automatic white balance to an image.
I found some official documentation about a balanceWhite() method: cv::xphoto::WhiteBalancer Class Reference
However, I have an obscure error when I try to call the function as shown in the example.
image = cv2.xphoto_WhiteBalancer.balanceWhite(image)
Raises:
Traceback (most recent call last):
File "C:\Users\Delgan\main.py", line 80, in load
image = cv2.xphoto_WhiteBalancer.balanceWhite(image)
TypeError: descriptor 'balanceWhite' requires a 'cv2.xphoto_WhiteBalancer' object but received a 'numpy.ndarray'
If then I try to use a cv2.xphoto_WhiteBalancer object as required:
balancer = cv2.xphoto_WhiteBalancer()
cv2.xphoto_WhiteBalancer.balanceWhite(balancer, image)
It raises:
Traceback (most recent call last):
File "C:\Users\Delgan\main.py", line 81, in load
cv2.xphoto_WhiteBalancer.balanceWhite(balancer, image)
TypeError: Incorrect type of self (must be 'xphoto_WhiteBalancer' or its derivative)
Did anyone succeeded to use this feature with Python 3.6 and OpenCV 3.4?
I also tried with derived classes GrayworldWB, LearningBasedWB and SimpleWB but errors are the same.

The answer can be found in the xphoto documentation.
The appropriate methods to create the WB algorithms are createSimpleWB(), createLearningBasedWB() and createGrayworldWB().
Example:
wb = cv2.xphoto.createGrayworldWB()
wb.setSaturationThreshold(0.99)
image = wb.balanceWhite(image)
Here is a sample file in the official OpenCV repository: modules/xphoto/samples/color_balance_benchmark.py

Related

rioaxrray open netcdf file result is a list not an xarray

I am trying to open a netcdf file using rioarray:
import rioxarray
import xarray
import raster
xds = rioxarray.open_rasterio(file, crs='+proj=latlong', masked=True)
but:
type(xds)
list
and xds has none of the attributes or methods of an xarray.
xds_lonlat = xds.rio.reproject("epsg:4326")
AttributeError Traceback (most recent call last)
in
----> 1 xds_lonlat = xds.rio.reproject("epsg:4326")
AttributeError: 'list' object has no attribute 'rio'
clipped = xds.rio.clip(mask.geometry, mask.crs, drop=False, invert=True)
AttributeError Traceback (most recent call last)
in
----> 1 clipped = xds.rio.clip(mask.geometry, mask.crs, drop=False, invert=True)
AttributeError: 'list' object has no attribute 'rio'
Can anyone advise?
I recently encountered this when I was opening a netCDF (with rioxarray) that had multiple variables. Since it returns a list, you would not expect it to have any of the rioxarray attributes or methods.
The documentation for the function is here: https://corteva.github.io/rioxarray/stable/rioxarray.html
One of the return types is List[xarray.Dataset], so I think this behavior is expected.
My guess is that you want one of the entries in the list like xds=xds[0], though it's hard to know without having more information about the file that you are opening.

'UnityEnvironment' object has no attribute 'behavior_spec'

I followed this link to doc to create environment of my own.
But when i run this
from mlagents_envs.environment import UnityEnvironment
env = UnityEnvironment(file_name="v1-ball-cube-game.x86_64")
env.reset()
behavior_names = env.behavior_spec.keys()
print(behavior_names)
Game window pop up and then terminal show error saying
Traceback (most recent call last):
File "index.py", line 6, in <module>
behavior_names = env.behavior_spec.keys()
AttributeError: 'UnityEnvironment' object has no attribute 'behavior_spec'
despite the fact that this is the exact snippet as shown in the documentation.
I created environment by following this (it make without brain) and i was able to train the model by .conf file. Now i wanted to connect to python API.
You need to use stable documents and stable repo( RELEASE_TAGS ) to achieve stable results. Unity ML Agents changes it's syntax every few months so that is problem if you are following master branch.
env.get_behavior_spec(behavior_name: str)
Should solve your problem.
https://github.com/Unity-Technologies/ml-agents/blob/release_2/docs/Python-API.md

How to use caffe convnet for object detection in video frames?

I have use codes from this link and sucessfully done the detection but the problem is it is only from webcam. I tried to modify the code so that it can read from file. the part I have modified is : I have written this
print("[INFO] starting video stream...")
vs= cv2.VideoCapture('cars.avi')
time.sleep(2.0)
fps = FPS().start()
# loop over the frames from the video stream
while True:
# grab the frame from the threaded video stream and resize it
# to have a maximum width of 400 pixels
frame = vs.read()
instead of this (code from the above link)
print("[INFO] starting video stream...")
vs = VideoStream(src=0).start()
time.sleep(2.0)
fps = FPS().start()
# loop over the frames from the video stream
while True:
# grab the frame from the threaded video stream and resize it
# to have a maximum width of 400 pixels
frame = vs.read()
For running the program from terminal I am using this command for both the cases:
python real_time_object_detection.py --prototxt
MobileNetSSD_deploy.prototxt.txt --model MobileNetSSD_deploy.caffemodel
The error I am getting when reading from file is
the error I am getting is :
C:\Users\DEBASMITA\AppData\Local\Programs\Python\Python35\real-time-object-
detection>python videoobjectdetection.py --prototxt
MobileNetSSD_deploy.prototxt.txt --model MobileNetSSD_deploy.caffemodel
[INFO] loading model...
Traceback (most recent call last):
File "videoobjectdetection.py", line 54, in <module>
frame = imutils.resize(frame, width=400)
File "C:\Users\DEBASMITA\AppData\Local\Programs\Python\Python35\lib\site-
packages\imutils\convenience.py", line 69, in resize
(h, w) = image.shape[:2]
AttributeError: 'tuple' object has no attribute 'shape'
I don't know where I am doing wrong. Please guide me.
I am unfamiliar with any of the code you are referencing, but the error is straightforward and similar errors hav been answered in other questions: You're trying to do a fancy method on a plain tuple object. Here's an example of this python concept using a common package, numpy for arrays:
#an example of the error you are getting with a plain tuple
>>>tup = (1,2,3,4)
>>>len(tup)
4
>>> tup.shape
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'shape'
#an example that uses an attribute called 'shape'
>>> import numpy as np
>>> x = np.array([1,2,3,4])
>>> x.shape
(4,)
>>> x.shape.shape
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'shape'
As you can see in my last two lines, the first time I call .shape on the numpy array, the call is valid. This call returns a tuple, so the last call to .shape.shape is invalid, it is operating on (4,). As for how to fix it? I don't know. For example, in this question the original poster thought that they were getting back some kind of image object, instead they were getting a tuple (maybe a tuple of image objects). Something similar is happening to you: Your VideoStream.read() call is returning a tuple. So when you call imutils.resize(frame, width=400) you are passing in a tuple, not an image or frame. So when that method tries to call .shape you get the error. VideoStream.read() may return a tuple by design, or an error condition. You'd have to read up on VideoStream to be sure.

OpenCV Error: Bad argument in ERClassifierNM1

I run opencv 3.2.0, ubuntu 14.04, and latest opencv_contrib.
I run examine:
https://github.com/opencv/opencv_contrib/blob/master/modules/text/samples/textdetection.py
But it have show err:
$ python textdetection.py scenetext_word01.jpg
textdetection.py
A demo script of the Extremal Region Filter algorithm described in:
Neumann L., Matas J.: Real-Time Scene Text Localization and Recognition, CVPR 2012
Extracting Class Specific Extremal Regions from 9 channels ...
(...) this may take a while (...)
OpenCV Error: Bad argument (Default classifier file not found!) in ERClassifierNM1, file /home/vietnam/opencv_and_contri/opencv_contrib/modules/text/src/erfilter.cpp, line 1022
Traceback (most recent call last):
File "textdetection.py", line 38, in <module>
erc1 = cv2.text.loadClassifierNM1(pathname+'/trained_classifierNM1.xml')
cv2.error: /home/vietnam/opencv_and_contri/opencv_contrib/modules/text/src/erfilter.cpp:1022: error: (-5) Default classifier file not found! in function ERClassifierNM1
How to solve this?
Try using relative paths in the parameters for cv2.text.loadClassifierNM1() and cv2.text.loadClassifierNM2()
So now that part of the code looks like this:
erc1 = cv2.text.loadClassifierNM1('./trained_classifierNM1.xml')
er1 = cv2.text.createERFilterNM1(erc1,16,0.00015,0.13,0.2,True,0.1)
erc2 = cv2.text.loadClassifierNM2('./trained_classifierNM2.xml')
er2 = cv2.text.createERFilterNM2(erc2,0.5)
I'm not sure why this works (it did for me), but I tried this after looking at a solution posted for a similar problem in VS2015 here: https://github.com/cesardelgadof/OpenCVBinaries/issues/1
Hope this helps.
Trying with absolute path e.g. "/usr/lib/opencv-3.2.0/opencv_contrib-3.2.0/modules/text/samples/trained_classifierNM1.xml" worked in my case for Ubuntu 16.04, C++

OpenCV Python save jpg specifying quality; gives SystemError

I just installed the newest OpenCV 2.4 on windows 7 (32bit)/ Python 2.7.3, but I still get the same error I got using the beta version:
>>> import cv2
>>> a = cv2.imread(r"DMap.jpg")
>>> a.shape
(1080, 1920, 3)
>>> cv2.imwrite('img_CV2_90.jpg', a, [cv2.IMWRITE_JPEG_QUALITY, 90])
Traceback (most recent call last):
File "<input>", line 1, in <module>
SystemError: error return without exception set
Any ideas ? Using tuple instead of list, or adding a trailing 0 to the sequence does not help - same error.
Thanks
- Sebastian Haase
It is probably due to some wrong wrapping of the imwrite() parameters from Python to C, cv2.IMWRITE_JPEG_QUALITY (which is of type "long"), and causes some weird problems. You should try to convert this constant to "int" type:
cv2.imwrite('img_CV2_90.jpg', a, [int(cv2.IMWRITE_JPEG_QUALITY), 90])
for me it solved the problem (python 2.7.2, opencv 2.4.1)

Categories

Resources