How to fix Numpy REFS_OK flag error? - python

I have the following code:
import cv2
import numpy as np
image = cv2.imread('pic1.png', cv2.IMREAD_GRAYSCALE)
height = 0
count = 0
it = np.nditer(image)
for(x) in it:
count += 1
if count == 80:
count = 0
height += 1
if x > 400:
print("Height is: " + height)
break
When I try to run the code I get the following error message:
TypeError: Iterator operand or requested dtype holds references, but the REFS_OK flag was not enabled
Why do I get this error? When I tried looking it up it seems like people just work around it instead of fixing it.

Check that the returned image variable isn't None.
Perhaps the image is not in the path your script is run from.
OpenCV doesn't raise an exception when it can't read/load the image, but, rather, returns None, in which case weird exceptions you will meet, when you try to operate on that None... like the exception posted.
(Sorry for speaking like Yoda... :-) )

Related

ValueError. What does that mean?

I've been following this tutorial and I'm currently on Project 2 chapter of it:
https://www.youtube.com/watch?v=WQeoO7MI0Bs&list=WL&index=90&t=9713s.
However when I start implementing the lines of code meant to read values off the image it gives out the following error:
ValueError: cannot reshape array of size 0 into shape (4,2)
From what I can tell, the error seems to be coming from this function:
def reorder(myPoints):
myPoints = myPoints.reshape((4,2))
myPointsNew = np.zeros((4,1,2),np.int32)
add = myPoints.sum(1)
print("add", add)
myPointsNew[0] = myPoints[np.argmin(add)]
myPointsNew[3] = myPoints[np.argmax(add)]
diff = np.diff(myPoints,axis=1)
myPointsNew[1] = myPoints[np.argmin(diff)]
myPointsNew[2] = myPoints[np.argmax(diff)]
print("New Points", myPointsNew)
However the problem is that I followed exactly how I saw on the tutorial and I couldn't come up with a solution. By the way the approximate time frame of this code in the video is at 2:45:00.

Error specifying the file path in Python

I am new to python and do not know it very well.
I want modified the online code to convert my image data to lmdb form.
I given the root of my src and dst like below:
paths_src = 'F:\caffe-windows\caffe-windows\data\sift-flow\test\'
path_dst = 'F:\caffe-windows\caffe-windows\data\sift-flow\testlmdb'
but after i run the code I got a error. it seem that my path is wrong? can anyone help? I also attach the code.
import os
import numpy as np
from scipy import io
import lmdb
import caffe
from PIL import Image
NUM_IDX_DIGITS = 10
IDX_FMT = '{:0>%d' % NUM_IDX_DIGITS + 'd}'
print '1111'
paths_src = 'F:\\caffe-windows\\caffe-windows\\data\\sift-flow\\test\\'
path_dst = 'F:\\caffe-windows\\caffe-windows\\data\\sift-flow\\testlmdb'
print '2222'
def img_to_lmdb(paths_src,path_dst):
in_db = lmdb.open(path_dst, map_size=int(1e9))
with in_db.begin(write=True) as in_txn:
for in_idx, in_ in enumerate(paths_src):
print 'img:::'+str(in_)
# load image:
# - as np.uint8 {0, ..., 255}
# - in BGR (switch from RGB)
# - in Channel x Height x Width order (switch from H x W x C)
im = np.array(Image.open(in_)) # or load whatever ndarray you need
im = im[:,:,::-1]
im = im.transpose((2,0,1))
im_dat = caffe.io.array_to_datum(im)
in_txn.put('{:0>10d}'.format(in_idx), im_dat.SerializeToString())
in_db.close()
img_to_lmdb(paths_src,path_dst)
print '3333'
I am not familiar with this library but your problem starts in this line-
for in_idx, in_ in enumerate(paths_src):
because paths_src is a string, which is iterable, the builtin function enumerate simply goes through each one of the characters in that string, so the first item would be the letter 'F' and not the entire path.
What you should do is define paths_src as a list. so instead of:
paths_src = 'F:\\caffe-windows\\caffe-windows\\data\\sift-flow\\test\\'
you should do:
paths_src = ['F:\\caffe-windows\\caffe-windows\\data\\sift-flow\\test\\']
Hope I was helpful.

Using python binding for flycapture to retrieve color image

I am working with the CMLN-13S2C-CS CCD camera from PointGrey Systems. It uses FlyCapture API to grab images. I would like to grab these images and do some stuff in OpenCV with them using python.
I am aware of the following python binding: pyflycapture2. With this binding I am able to retrieve images. However, I cannot retrieve the images in color, which is what the camera should be able to do.
The videomode and framerate that the camera is able to handle are VIDEOMODE_1280x960Y8, and FRAMERATE_15, respectively. I think it has something to do with the pixel_format, which I think should be raw8.
Is anyone able to retrieve a color image using this or any existing python binding for flycapture? Note that I am working on Linux.
You don't need to use the predefined modes. The Context class has the set_format7_configuration(mode, x_offset, y_offset, width, height, pixel_format) method with which you can use your custom settings. Using this you can at least change the resolution of the grabbed image.
Usage example:
c.set_format7_configuration(fc2.MODE_0, 320, 240, 1280, 720, fc2.PIXEL_FORMAT_MONO8)
As for the coloring issue. I've so far managed to get a colored image using PIXEL_FORMAT_RGB8 and modifying the Image class in flycapture2.pyx as follows:
def __array__(self):
cdef np.ndarray r
cdef np.npy_intp shape[3] # From 2 to 3
cdef np.dtype dtype
numberofdimensions = 2 # New variable
if self.img.format == PIXEL_FORMAT_MONO8:
dtype = np.dtype("uint8")
elif self.img.format == PIXEL_FORMAT_MONO16:
dtype = np.dtype("uint16")
elif self.img.format == PIXEL_FORMAT_RGB8: # New condition
dtype = np.dtype("uint8")
numberofdimensions = 3
shape[2] = 3
else:
dtype = np.dtype("uint8")
Py_INCREF(dtype)
shape[0] = self.img.rows
shape[1] = self.img.cols
# nd value (numberofdimensions) was always 2; stride set to NULL
r = PyArray_NewFromDescr(np.ndarray, dtype,
numberofdimensions, shape, NULL,
self.img.pData, np.NPY_DEFAULT, None)
r.base = <PyObject *>self
Py_INCREF(self)
return r
This code is most likely not flawless (i.e I removed the stride stuff) for the simple reason that I have pretty much 0 experience with C and Cython but this way I at least managed to get a colored frame (now in the process of trying to get the PIXEL_FORMAT_RAW8 working).
And just as a reminder: the flycapture2.pyx is a Cython file so you need to recompile it before you can use it (I just run the pyflycap2 install script again).
I'm using the same camera with Matlab and also got an issues with "raw8" format. So, I've chose "rgb8", specifically, "F7_RGB_644x482_Mode1" and all things starts to work (not sure, how it should look at Python).
P.S. At the moment I'm trying to start work with Python and pyflycapture2, let's see, if I would be able to find workaround.
UPD: Okay, now I know the things. :)
Your (and mine) issue reasons are buried inside the pyflycapture2 itself, especially "Image" class definition. You can have a look here: https://github.com/jordens/pyflycapture2/blob/eec14acd761e89d8e63a0961174e7f5900180d54/src/flycapture2.pyx
if self.img.format == PIXEL_FORMAT_MONO8:
dtype = np.dtype("uint8")
stride[1] = 1
elif self.img.format == PIXEL_FORMAT_MONO16:
dtype = np.dtype("uint16")
stride[1] = 2
else:
dtype = np.dtype("uint8")
stride[1] = self.img.stride/self.img.cols
ANY image will be converted into grayscale, even if it was RGB initially. So, we need to update that file somehow.

Inappropriate argument value (of correct type). in JES (Python/Jython)

Hey so I am just working on some coding homework for my Python class using JES. Our assignment is to take a sound, add some white noise to the background and to add an echo as well. There is a bit more exacts but I believe I am fine with that. There are four different functions that we are making: a main, an echo equation based on a user defined length of time and amount of echos, a white noise generation function, and a function to merge the noises.
Here is what I have so far, haven't started the merging or the main yet.
#put the following line at the top of your file. This will let
#you access the random module functions
import random
#White noise Generation functiton, requires a sound to match sound length
def whiteNoiseGenerator(baseSound) :
noise = makeEmptySound(getLength(baseSound))
index = 0
for index in range(0, getLength(baseSound)) :
sample = random.randint(-500, 500)
setSampleValueAt(noise, index, sample)
return noise
def multipleEchoesGenerator(sound, delay, number) :
endSound = getLength(sound)
newEndSound = endSound +(delay * number)
len = 1 + int(newEndSound/getSamplingRate(sound))
newSound = makeEmptySound(len)
echoAmplitude = 1.0
for echoCount in range (1, number) :
echoAmplitude = echoAmplitude * 0.60
for posns1 in range (0, endSound):
posns2 = posns1 + (delay * echoCount)
values1 = getSampleValueAt(sound, posns1) * echoAmplitude
values2 = getSampleValueAt(newSound, posns2)
setSampleValueAt (newSound, posns2, values1 + values2)
return newSound
I receive this error whenever I try to load it in.
The error was:
Inappropriate argument value (of correct type).
An error occurred attempting to pass an argument to a function.
Please check line 38 of C:\Users\insanity180\Desktop\Work\Winter Sophomore\CS 140\homework3\homework_3.py
That line of code is:
setSampleValueAt (newSound, posns2, values1 + values2)
Anyone have an idea what might be happening here? Any assistance would be great since I am hoping to give myself plenty of time to finish coding this assignment. I have gotten a similar error before and it was usually a syntax error however I don't see any such errors here.
The sound is made before I run this program and I defined delay and number as values 1 and 3 respectively.
Check the arguments to setSampleValueAt; your sample value must be out of bounds (should be within -32768 - 32767). You need to do some kind of output clamping for your algorithm.
Another possibility (which indeed was the error, according to further input) is that your echo will be out of the range of the sample - that is, if your sample was 5 seconds long, and echo was 0.5 seconds long; or the posns1 + delay is beyond the length of the sample; the length of the new sound is not calculated correctly.

what are the cv.Scalar (min) and (max) used in cv.IntRanges

I've searched and searched but couldn't find:
When I use cv.InRanges I need to place a min and max HSV values. In all the examples I have seen so far they use Cv.Scalar on constants
i tried using it myself but couldnt figure what should be there i tried a list, a tuple and numpy.array all with three values and i keep getting errors.
"a float is requierd" for a list
"a float is required" for tuple
"only length -1 arrays can be converted to python scalars" for numpy.array
Though come to think of it array and list should be the same....
Can anyone please tell me how to use it properly, this is a sample of one of many tries:
def thresh(img, pixel):
hsv_min = pixel
hsv_min[0] = hsv_min[0] - 5
hsv_min[1] = hsv_min[1] - 20
hsv_min[2] = hsv_min[2] - 20
hsv_max[0] = hsv_max[0] + 5
hsv_max[1] = 255
hsv_max[2] = 255
cv.InRangeS(ingHSV, cv.Scalar(hsv_min), cv,Scalar(hsv_max), imgThreshold)
So i figured it out:
using:
cv.Scalar(float(hsv_min[0]),float(hsv_min[1]),float(hsv_min[2]))
and then Cv.InRangeS works fine.
Maybe this code can help you, but it uses numpy & opencv2, I've never tried with opencv first.
import cv2
import numpy
def thresh(img, pixel):
hsv_min = pixel
low_threshold = numpy.array(( hsv_min[0] - 5, hsv_min[1] - 20, hsv_min[2] - 20), dtype=numpy.uint8, ndmin=1)
high_threshold = numpy.array(( hsv_max[0] + 5, 255, 255), dtype=numpy.uint8, ndmin=1)
cv2.InRange(ingHSV, low_threshold, high_threshold, imgThreshold)

Categories

Resources