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)
Related
I am currently writing a function for a CPPN to map RGB coordinates of an input image, for some artistic work. I am working from some base code which allows the network to map XY coordinates, and attempting to modify the code. This particular error message is haunting me - I know that I am passing through an incorrect data form somehow, but having tried many things from SO, thought on it, and referred to documentation repeatedly I continue to hit this wall.
I am curious if I am missing something obvious as a relative beginner, or is there something else wrong with this function? I'm feeling that perhaps linspace is not the right route, I have tried a couple of others (meshgrid, mgrid) without joy. Any help very much appreciated.
I originally met the error when trying to pass through whole arrays such as image[0:].
So, I tried to modify it so that it passes through single values of the R, G, and B arrays via for loops, then converts the values back to arrays in the correct shape, and meshes together in an RGB map at the end (if only I could get so far!).
Find below the code:
#smaller_img is a variable defined earlier in the code, which is a resized image from skimage dataset
image = gray2rgb(smaller_img)
def RGBMAP(image):
redvals = []
red = image[0:]
for i in red:
r = np.linspace(0,255, i)
redvals.append(r)
redvals = np.asarray(redvals)
redvals.reshape([64,64,3])
greenvals = []
green = image[1:]
for i in green:
g = np.linspace(0,255,i)
greenvals.append(g)
greenvals = np.asarray(greenvals)
greenvals.reshape([63,64,3])
bluevals = []
blue = image[2:]
for i in blue:
b = np.linspace(0,255,i)
bluevals = np.asarray(bluevals)
bluevals.reshape([62,64,3])
rgb_grid = np.stack(np.meshgrid(redvals,greenvals,bluevals),axis=1)
return rgb_grid
I am consistently meeting the following error at the same point (first calling of linspace):
23 #array_function_dispatch(_linspace_dispatcher)
24 def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None,
25 axis=0):
26 """
27 Return evenly spaced numbers over a specified interval.
28
(...)
118
119 """
--> 120 num = operator.index(num)
121 if num < 0:
122 raise ValueError("Number of samples, %s, must be non-negative." % num)
TypeError: only integer scalar arrays can be converted to a scalar index
Thank you for any input.
I am working on a problem which involves a batch of 19 tokens each with 400 features. I get the shape (19,1,400) when concatenating two vectors of size (1, 200) into the final feature vector. If I squeeze the 1 out I am left with (19,) but I am trying to get (19,400). I have tried converting to list, squeezing and raveling but nothing has worked.
Is there a way to convert this array to the correct shape?
def attn_output_concat(sample):
out_h, state_h = get_output_and_state_history(agent.model, sample)
attns = get_attentions(state_h)
inner_outputs = get_inner_outputs(state_h)
if len(attns) != len(inner_outputs):
print 'Length err'
else:
tokens = [np.zeros((400))] * largest
print(tokens.shape)
for j, (attns_token, inner_token) in enumerate(zip(attns, inner_outputs)):
tokens[j] = np.concatenate([attns_token, inner_token], axis=1)
print(np.array(tokens).shape)
return tokens
The easiest way would be to declare tokens to be a numpy.shape=(19,400) array to start with. That's also more memory/time efficient. Here's the relevant portion of your code revised...
import numpy as np
attns_token = np.zeros(shape=(1,200))
inner_token = np.zeros(shape=(1,200))
largest = 19
tokens = np.zeros(shape=(largest,400))
for j in range(largest):
tokens[j] = np.concatenate([attns_token, inner_token], axis=1)
print(tokens.shape)
BTW... It makes it difficult for people to help you if you don't include a self-contained and runnable segment of code (which is probably why you haven't gotten a response on this yet). Something like the above snippet is preferred and will help you get better answers because there's less guessing at what your trying to accomplish.
I have a series of maps with two different indices, i and j. Let this be indexed like map_series[i][j].
EDIT 1/21: A minimal working example would be something like
map_series=np.array([np.array([np.arange(12) + 0.1*(i+1) + 0.01*(j+1) for j in range(3)]) for i in range(5)])
I'd like to apply the same mask to each; if map_series is one-dimensional, these each work.
I can imagine a few different ways of applying these maps:
(A) Applying the mask to the whole array:
map_series_ma = hp.ma(map_series)
map_series_ma.mask = predefined_mask
(B1) Applying the mask to each element of the array:
map_series_ma = np.zeros_like(map_series)
for i in range(len(map_series)):
for j in range(len(map_series[0])):
temp = hp.ma(map_series[i][j])
temp.mask = predefined_mask
map_series_ma[i][j] = temp
(B2) Applying the mask to each element of the array:
map_series_ma = np.zeros_like(map_series)
for i in range(len(map_series)):
for j in range(len(map_series[0])):
map_series_ma[i][j] = hp.ma(map_series[i][j])
map_series_ma[i][j].mask = predefined_mask
(C) Pythonically enumerating the list:
map_series_ma = np.array([hp.ma(map_series[i][j]) for j in range(j_max) for i in range(i_max)])
map_series_ma.mask = predetermined_mask
All of these fail to give my desired output, however.
Upon trying (A) or (C) I get an error after the first step, telling me TypeError: bad number of pixels.
Upon trying (B1) I don't get an error, but I also none of the elements of the maps_series_ma have masks; in fact, they do not even appear to be hp.ma objects. Oddly enough, though: when I return temp it does have the appropriate mask.
Upon trying (B2) I get the error
AttributeError: 'numpy.ndarray' object has no attribute 'mask' (which, after looking at my syntax, I totally understand!)
I'm a little confused how to go about this. Both (A) and (B1) seem acceptable to me...
Any help is much appreciated,
Thanks,
Sam
this works for me:
import numpy as np
import healpy as hp
map_series=np.array([np.array([np.arange(12) + 0.1*(i+1) + 0.01*(j+1) for j in range(3)]) for i in range(5)])
map_series_ma = map(lambda x: hp.ma(x), map_series)
pm=[True, True,True,True,True,True,False,False,False,False,False,False]
for m in map_series_ma:
for mm in m:
mm.mask=pm
I'm writing a program using bitarray
for example:
bytePerInt = sys.getsizeof(1)
class BitMap(object):
def __init__(self,bits):
self.bitsPerInt = 8*bytePerInt
size = bits/self.bitsPerInt+1
self.bitarray = [0]*size
#set the bit of pos as 1
def setBit(self,pos):
index = pos/self.bitsPerInt
shift = pos%self.bitsPerInt
operator = self.bitarray[index]
mask = 1<<shift
operator|=mask
self.bitarray[index] = operator
I want to get the modulus with adding instead of %, such as num&31 instead of num%32.
However, bytePerInt is 24 in my computer, bitsPerInt is 24*8=192, which is not a power-of-2-number, as a result, I can't anding 191 to get the modulus, so what I can do?
Like others I'm not sure what you mean by and the essential element in the array is Int, but if you are creating a bit array of booleans (1 and 0), use bitarray.
I would like to know how I can round a number in numpy to an upper or lower threshold which is function of predefined step size. Hopefully stated in a clearer way, if I have the number 123 and a step size equal to 50, I need to round 123 to the closest of either 150 or 100, in this case 100. I came out with function below which does the work but I wonder if there is a better, more succint, way to do this.
Thanks in advance,
Paolo
def getRoundedThresholdv1(a, MinClip):
import numpy as np
import math
digits = int(math.log10(MinClip))+1
b = np.round(a, -digits)
if b > a: # rounded-up
c = b - MinClip
UpLow = np.array((b,c))
else: # rounded-down
c = b + MinClip
UpLow = np.array((c,b))
AbsDelta = np.abs(a - UpLow)
return UpLow[AbsDelta.argmin()]
getRoundedThresholdv1(143, 50)
The solution by pb360 is much better, using the second argument of builtin round in python3.
I think you don't need numpy:
def getRoundedThresholdv1(a, MinClip):
return round(float(a) / MinClip) * MinClip
here a is a single number, if you want to vectorize this function you only need to replace round with np.round and float(a) with np.array(a, dtype=float)
Summary: This is a correct way to do it, the top answer has cases that do not work:
def round_step_size(quantity: Union[float, Decimal], step_size: Union[float, Decimal]) -> float:
"""Rounds a given quantity to a specific step size
:param quantity: required
:param step_size: required
:return: decimal
"""
precision: int = int(round(-math.log(step_size, 10), 0))
return float(round(quantity, precision))
My reputation is too low to post a comment on the top answer from Ruggero Turra and point out the issue. However it has cases which did not work for example:
def getRoundedThresholdv1(a, MinClip):
return round(float(a) / MinClip) * MinClip
getRoundedThresholdv1(quantity=13.200000000000001, step_size=0.0001)
Returns 13.200000000000001 right back whether using numpy or the standard library round. I didn't even find this by stress testing the function. It just came up when using it in production code and spat an error.
Note full credit for this answer comes out of an open source github repo which is not mine found here
Note that round() in Ruggero Turra his answer rounds to the nearest even integer. Meaning:
a= 0.5
round(a)
Out: 0
Which may not be what you expect.
In case you want 'classical' rounding, you can use this function, which supports both scalars and Numpy arrays:
import Numpy as np
def getRoundedThresholdv1(a, MinClip):
scaled = a/MinClip
return np.where(scaled % 1 >= 0.5, np.ceil(scaled), np.floor(scaled))*MinClip
Alternatively, you could use Numpy's method digitize. It requires you to define the array of your steps. digitize will kind of ceil your value to the next step. So in order to round in a 'classical' way we need an intermediate step.
You can use this:
import Numpy as np
def getRoundedThresholdv1(a, MinClipBins):
intermediate = (MinClipBins[1:] + MinClipBins[:-1])/2
return MinClipBins[np.discritize(a, intermediate)]
You can then call it like:
bins = np.array([0, 50, 100, 150])
test1 = getRoundedThresholdv1(74, bins)
test2 = getRoundedThresholdv1(125, bins)
Which gives:
test1 = 50
test2 = 150