set comprehension syntax error using numpy - python

I'm trying to pick random zone in an image using numpy.
I'm using a python set to ensure that all my zones are unique, however, later when trying to generate a mask from this set, I'm getting an "SyntaxError: invalid syntax"
here is the code I'm using:
def _get_positions(self):
small_shape = int(self._width / MACROPIXEL_SIZE)
small_mask = numpy.zeros((small_shape, small_shape), dtype=numpy.uint8)
#how many macropixel we will pick
nb_pick = int((small_shape * small_shape) * self._alter_percentage)
position_set = set()
#try again until we pick 'nb_pick' unique positions
while len(position_set) < nb_pick:
pick = numpy.random.choice(small_shape, 2)
position_set.add((pick[0], pick[1]))
# mark the selected pixels
{small_mask[pos_x][pos_y]=1 for (pos_x, pos_y) in position_set}
# full size mask
self.mask = numpy.kron(small_mask, numpy.ones(self._height, self._width))
code explanation:
I need to process a lot of images, so I'm trying to optimize my code
I'm trying to pick random zones using a simpler version of this image (this is the 'small shape' and 'small mask').
when the set is full of unique positions, I'm using it to mark on the mask which part of the image where selected
and at last, I'm rescaling the mask
why the set comprehension give a syntax error ? what am I doing wrong ?
--edit--
error trace:
Traceback (most recent call last):
File "test_random_alteration.py", line 27, in <module>
import alter_labels
File "/home/abgrall/segmentation/loreal/histo_erp_fm/alter_labels.py", line 56
{small_mask[pos_x][pos_y]=1 for (pos_x, pos_y) in position_set}
^
SyntaxError: invalid syntax

You can not the set comprehension that you are using here
{small_mask[pos_x][pos_y]=1 for (pos_x, pos_y) in position_set}
these comprehensions are for creating sets of objects. You are using it to assign a value to an array - which is invalid syntax.
Instead,
for pos_x, pos_y in position_set:
small_mask[pos_x][pos_y] = 1
However, if you are trying to make this more efficient, you can complitly vectorize your random selection of the pos_x, pos_y pairs and vectorize the access on small_mask.
def _get_positions(self):
small_shape = int(self._width / MACROPIXEL_SIZE)
small_mask = numpy.zeros((small_shape, small_shape), dtype=numpy.uint8)
#how many macropixel we will pick
nb_pick = int((small_shape * small_shape) * self._alter_percentage)
nx, ny = small_shape, small_shape
xy = np.mgrid[:nx,:ny].reshape(2, -1).T
pos = xy.take(np.random.choice(xy.shape[0], nb_pick, replace=False), axis=0)
small_mask[pos] = 1
self.mask = numpy.kron(small_mask, numpy.ones(self._height, self._width))

Related

TypeError: Can't convert vector element for 'scores', index=0

I'm trying to take the output of a yolov5s.onnx model and and run NMSBoxes on it. But I keep getting this error:
Traceback (most recent call last):
File "python_detection.py", line 132, in <module>
class_ids, confidences, boxes = wrap_detection(inputImage, outs[0])
File "python_detection.py", line 88, in wrap_detection
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.25, 0.45)
TypeError: Can't convert vector element for 'scores', index=0
Everywhere I look, people are using the exact same code as me. Which makes sense, since this code was mostly copied from a tutorial. So I don't know what I'm doing so wrong that keeps giving me this error.
Here's the full function:
def wrap_detection(input_image, output_data):
class_ids = []
confidences = []
boxes = []
rows = output_data.shape[0]
image_width, image_height, _ = input_image.shape
x_factor = image_width / INPUT_WIDTH
y_factor = image_height / INPUT_HEIGHT
for r in range(rows):
row = output_data[r]
confidence = row[4]
if confidence >= 0.4:
classes_scores = row[5:]
_, _, _, max_indx = cv2.minMaxLoc(classes_scores)
class_id = max_indx[1]
if (classes_scores[class_id] > .25):
confidences.append(confidence)
class_ids.append(class_id)
x, y, w, h = row[0].item(), row[1].item(), row[2].item(), row[3].item()
left = int((x - 0.5 * w) * x_factor)
top = int((y - 0.5 * h) * y_factor)
width = int(w * x_factor)
height = int(h * y_factor)
box = np.array([left, top, width, height])
boxes.append(box)
'''
Print the raw output
'''
# Save output
np.set_printoptions(threshold=sys.maxsize)
file = open("python_raw_model_output.txt", "w+")
for i in range(len(boxes)):
file.write(str(boxes[i]) + " " + str(confidences[i]) + " " + str(class_ids[i]))
file.write("\n")
file.close()
# NMS on the lists
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.25, 0.45)
result_class_ids = []
result_confidences = []
result_boxes = []
for i in indexes:
result_confidences.append(confidences[i])
result_class_ids.append(class_ids[i])
result_boxes.append(boxes[i])
return result_class_ids, result_confidences, result_boxes
I had the same issue. It seemed to be related to the cuda configuration as it works fine on the cpu. I did not figure out exactly what was wrong but I worked around the issue by using fastNMS: enter link description here
I dont know if you still need help, but for anyone that comes across this problem like I did, the fix is that you need to make sure that the Python version you're using is Python>=3.8 and the opencv version is atleast 4.5.4.
Using pip install opencv-python==4.5.5.64 fixed my problem.
For others who come across this issue, I was able to get around the same (on Python 3.8.10 and OpenCV 4.5.3) by making confidences a Numpy array (instead of a list). The answers pointing at CUDA or Python/OpenCV versions are probably still right, but this may be a simpler solution for some situations.

Getting this error: "new style getargs format but argument is not a tuple" | opencv, python

I am currently developing a method for detecting and logging camera 'wobble', this will eventually be running parallel to various object detection, and tracking models. I am very new to opencv, although I have a fair bit of general programming experience.
It is very early days, and I am currently experimenting with different technologies, however, I am having some trouble.
I keep getting the following error:"new style getargs format but argument is not a tuple" whenever I run the code below.
The issue occurs after invocation of the cv2.createHanningWindow() function. I believe it is an issue with the parameterization, I just cant figure it out.
I understand this issue is most likely trivial, however, I appreciate any, and all help.
Thanks for the help!
import cv2
import glob
import numpy as np
import math
path = "New folder\\*.jpg"
frames = [cv2.imread(file) for file in glob.glob(path)]
n=0
h, w, c = frames[0].shape
x = int(w)
hann= frames[0].copy()
while n < len(frames):
#do if first frame
if n == 0:
initial = frames[n]
prev = initial.copy()
cv2.createHanningWindow(hann, x)
shift = cv2.phaseCorrelate(initial, prev, hann)
radius = math.sqrt(shift.x*shift.x + shift.y*shift.y)
if radius > 5:
#draw circle and line showing shift direction
center=h, w
cv2.circle(frames[n], center, 5, (0, 0, 255), 2)
cv2.line(frames[n], center, (center.x+shift.x, center.y+shift.y), (0,255,0), 2)
cv2.imshow('frame', frames[n])
key = cv2.waitKey(3000)
if key == 27:
break
prev = frames[n].copy()
n=n+1
cv2.destroyAllWindows()
<ipython-input-30-3889c798574e> in <module>
22 initial = frames[n]
23 prev = initial.copy()
---> 24 cv2.createHanningWindow(hann, x)
25
26 shift = cv2.phaseCorrelate(initial, prev, hann)
SystemError: new style getargs format but argument is not a tuple

How to get the name of the variable in an array, to be used as part of another statement?

I was creating a new script in which I generate an array that contains a list of strings(g='g_o.DisplacementMultiplier_'+str(y+1), wherey varies from 0 to 400).
This later has to be used to set four properties in a third party software, but I see that the syntax I'm using set the properties for the variable g and not for g_o.DisplacementMultiplier_#).
Attached is the code:
import smtplib
import math
import time
import imp
import numpy as np
s_o,g_o=new_server
s_o.new()
# Geometry
Bench = 5 # Crest bench
Angle = 23
Height = 15.3
# Frequencies
fz=[]
Tmin=0.01
Tmax=4
Tstep=0.01
Ts = np.arange(Tmin, (Tmax+Tstep), Tstep)
fz = float(1)/Ts
# Calculate x-lenght of slope
dtot= Height / math.tan(math.pi*Angle/180)
# Calculate xmax
xmax = (2 * dtot)+ Bench
# Displacement
g_o.linedispl (0, 0, xmax, 0)
g_o.set(g_o.Line_1.LineDisplacement.Displacement_x, "Prescribed")
g_o.set(g_o.Line_1.LineDisplacement.Displacement_y, "Fixed")
g_o.set(g_o.Line_1.LineDisplacement.ux_start, 1)
# Generate displc multipliers
for y in range (0, len(fz)):
g_o.displmultiplier()
g='g_o.DisplacementMultiplier_'+str(y+1)
g_o.set(g[y].Amplitude, 10)
g_o.set(g[y].DataType, "Accelerations")
g_o.set(g[y].Frequency, fz[y])
The error from the code is:
g_o.set(g[y].Amplitude, 10)
AttributeError: 'str' object has no attribute 'Amplitude'
If i understood your question correctly, your trying to accessing property dynamically.
Remove the following line in bottom for loop
g='g_o.DisplacementMultiplier_'+str(y+1)
Change following these lines
g_o.set(g[y].Amplitude, 10)
g_o.set(g[y].DataType, "Accelerations")
g_o.set(g[y].Frequency, fz[y])
to
g_o.set(g_o['DisplacementMultiplier_'+str(y+1)].Amplitude, 10)
g_o.set(g_o['DisplacementMultiplier_'+str(y+1)].DataType, "Accelerations")
g_o.set(g_o['DisplacementMultiplier_'+str(y+1)].Frequency, fz[y])

Python, Cv2, numpy to detect a picture in another picture

I am using these codes to detect if a small picture is a part of a big picture. (or take it as, if the small picture can be found in the big picture)
this is the BIG picture
this is the SMALL picture
It works fine and give me the x_coordinate of where the small picture starts.
import cv2
import numpy as np
big_pic = cv2.imread("c:\\big.jpg")
small_pic = cv2.imread('c:\\small.jpg')
res = cv2.matchTemplate(big_pic,small_pic,cv2.TM_CCOEFF_NORMED)
threshold = 0.99
loc = np.where (res >= threshold)
x_coordinate = list(loc[0])
print x_coordinate
However, when I want to specify the detection area in the big picture – that is, if the small picture can be found in certain part of the big picture – it fails.
big_pic = cv2.imread("c:\\big.jpg")
target_area = big_pic[0:0, 238:220]
small_pic = cv2.imread('c:\\small.jpg')
res = cv2.matchTemplate(target_area,small_pic,cv2.TM_CCOEFF_NORMED)
threshold = 0.99
loc = np.where (res >= threshold)
x_coordinate = list(loc[0])
print x_coordinate
The error says:
OpenCV Error: Assertion failed (corrsize.height <= img.rows + templ.rows - 1 && corrsize.width <= img.cols + templ.cols - 1) in cv::crossCorr, file ......\opencv-3.1.0\modules\imgproc\src\templmatch.cpp, line 658
Traceback (most recent call last):
File "C:\Python27\finding picture.py", line 8, in
res = cv2.matchTemplate(target_area,small_pic,cv2.TM_CCOEFF_NORMED)
cv2.error: ......\opencv-3.1.0\modules\imgproc\src\templmatch.cpp:658: error: (-215) corrsize.height <= img.rows + templ.rows - 1 && corrsize.width <= img.cols + templ.cols - 1 in function cv::crossCorr
What went wrong? Thank you.
It seems [y,y1 : x,x1] is the right format. So the credit shall go to #ZdaR.
Just to post an edited example, using a rectangle shape SMALL.
this is the BIG picture
this is the SMALL picture
The target area is,
[0,0] [300,220]. # Reading as [x, y] and [x1, y1].
They are the top left point and bottom right point in the BIG.
Made the code as following:
big_pic = cv2.imread("c:\\big.jpg")
target_area = big_pic[0:220, 0:300] # [y,y1 : x,x1] # it returns a result.
target_area = big_pic[0:300, 0:220] # [x,x1 : y,y1] # it doesn’t return a result.
small_pic = cv2.imread('c:\\small.jpg')
res = cv2.matchTemplate(target_area,small_pic,cv2.TM_CCOEFF_NORMED)
threshold = 0.99
loc = np.where (res >= threshold)
x_coordinate = list(loc[0])
print x_coordinate

Image Interpolation in python

I am trying to use interpolation to remove chromatic aberration from an image. The code I have generates the following error: TypeError: unhashable type: 'numpy.ndarray'. Below is my code - any help would be greatly appreciated. Thank you- Areej
This is an input explanation
#splitting an image into its separe bands
source = im.split()
Cfixed = source[2]
Cwarp = source[1]
#take the image minus a ew-wide edge
roi = [ew+1, xdim-ew, ew+1, ydim-ew];
roi_pad = [roi[0]-ew, roi[1]+ew, roi[2]-ew, roi[3]+ew];
for k in range(0,centers_x.size):
cx = centers_x[k]
cy = centers_y[k]
wz = warps[k]
import scipy as sp
from scipy import interpolate
def warpRegion(Cwarp, roi_pad, (cx, cy, wz)):
#Unpack region indices
sx, ex, sy, ey = roi_pad
xramp, yramp = np.mgrid[sx:ex+1, sy:ey+1]
shapeofgrid=xramp.shape
print 'shape of x grid'+str(shapeofgrid)
xrampc = xramp - cx;
yrampc = yramp - cy;
xramp1 = 1/wz*xrampc;
yramp1 = 1/wz*yrampc;
xrampf = xrampc.flatten()
yrampf = yrampc.flatten()
xramp1f = xramp1.flatten()
yramp1f = yramp1.flatten()
reg_w = sp.interpolate.interp2d(yrampf,xrampf,Cwarp, yramp1f, xramp1f,'cubic');
A possible explanation of the error message is that you are trying to use a NumPy array as a dict key or a set element. Look at where the error occurs and study the type of every variable referenced on that line. If you need help, post a runnable example and the full traceback of the exception.
I would recommend using PIL. (Python Image Library)
http://www.pythonware.com/products/pil/
One method would be to:
Generate a list of top colours per quadrant/sample area and hash the list

Categories

Resources