How to turn a numpy array to a numpy object?

2024/11/16 13:42:12

I have a NumPy array as follows:

[[[  0   0]][[  0 479]][[639 479]][[639   0]]]

and I would like to convert it into something like so:

[(  0   0)(  0 479)(639 479)(639   0), dtype=dtype([('x', '<i2'), ('y', '<i2')])]

I have tried to use the following function:

def flat(contour):for point in contour:yield tuple(point[0])

like so:

contour=np.fromiter(flat(contour),Point)

but this gives me the following error: ValueError: setting an array element with a sequence. so how can I turn certain "dimensions" of a NumPy array into NumPy "objects" (or whatever else they are called in NumPy)

Answer
In [117]: arr = np.array([[[0,0]],[[0,479]],[[639,479]],[[639,0]]])                                  
In [118]: arr                                                                                        
Out[118]: 
array([[[  0,   0]],[[  0, 479]],[[639, 479]],[[639,   0]]])
In [119]: arr.shape                                                                                  
Out[119]: (4, 1, 2)

You apparently want a structured array, https://numpy.org/devdocs/user/basics.rec.html#

There's a handy tool for converting a numeric array to a structured one:

In [120]: import numpy.lib.recfunctions as rf                                                        
In [121]: rf.unstructured_to_structured(arr,names=['x','y'])                                         
Out[121]: 
array([[(  0,   0)],[(  0, 479)],[(639, 479)],[(639,   0)]], dtype=[('x', '<i8'), ('y', '<i8')])
In [122]: _.shape                                                                                    
Out[122]: (4, 1)

or using your desired dtype:

In [126]: rf.unstructured_to_structured(arr,dtype=np.dtype([('x', '<i2'), ('y', '<i2')]))            
Out[126]: 
array([[(  0,   0)],[(  0, 479)],[(639, 479)],[(639,   0)]], dtype=[('x', '<i2'), ('y', '<i2')])

or create a 'blank' array with the desired dtype and shape, and assign fields:

In [127]: res = np.zeros((4,1), dtype=np.dtype([('x', '<i2'), ('y', '<i2')]))                        
In [128]: res                                                                                        
Out[128]: 
array([[(0, 0)],[(0, 0)],[(0, 0)],[(0, 0)]], dtype=[('x', '<i2'), ('y', '<i2')])
In [129]: res['x'] = arr[:,:,0]                                                                      
In [130]: res['y'] = arr[:,:,1]                                                                      
In [131]: res                                                                                        
Out[131]: 
array([[(  0,   0)],[(  0, 479)],[(639, 479)],[(639,   0)]], dtype=[('x', '<i2'), ('y', '<i2')])

Or from a list of tuples (list of lists of tuples in your case):

In [132]: arr.tolist()                                                                               
Out[132]: [[[0, 0]], [[0, 479]], [[639, 479]], [[639, 0]]]In [134]: [[tuple(i) for i in x] for x in arr.tolist()]                                              
Out[134]: [[(0, 0)], [(0, 479)], [(639, 479)], [(639, 0)]]In [135]: np.array([[tuple(i) for i in x] for x in arr.tolist()], dtype=[('x', '<i2'), ('y', '<i2')])...:                                                                                            
Out[135]: 
array([[(  0,   0)],[(  0, 479)],[(639, 479)],[(639,   0)]], dtype=[('x', '<i2'), ('y', '<i2')])
https://en.xdnf.cn/q/119524.html

Related Q&A

recover all line from an attribute in a database in json

To simplify my problem, I have a base in json, and I recover all of my lines of json to put informations in a base. It seems easy for moments, but problem is that my json is not correctly writtenSo i…

Calculate eigen value in python as same way(order) in Matlab

This is the Matlab code which is returning eigenvector in V and eigenvalue in D. Consider C is 9*9 matrix then V is 9*9 matrix and D is 9*9 diagonal. matrix.[V,D] = eig(C);I want the same thing in Pyth…

Python: ctypes and Pointer to Structure

I am trying to make a pointer of a struct and then de-reference it. But its crashing. I have mimiced the behvior here with this simple code. from ctypes import * import ctypesclass File(Structure):_fie…

Python:Why readline() function doesnt work for file looping

I have the following code:#!/usr/bin/pythonf = open(file,r)for line in f:print line print Next line , f.readline() f.close()This gives the following output:This is the first lineNext line That was the …

How to replace cropped rectangle in opencv?

I have managed to cropped a bounding box with text, e.g. given this image:Im able to exact the following box:with this code: import re import shutilfrom IPython.display import Imageimport requests impo…

How can I read hexadecimal data with python?

I have this c# app that Im trying to cooperate with a app written in python. The c# app send simple commands to the python app, for instance my c# app is sending the following:[Flags]public enum GameRo…

Want to scrape all the specific href from the a tag

I have search the specific brand Samsung , for this number of products are search ,I just wanted to scrape all the href from the of the search products with the product name . enter code here import u…

Encryption code in def function to be written in python

need some help in the following code as it goes into infinite loop and does not validate user input: the get_offset is the function. Just edited need some help with the encryption part to be done in a …

Creating xml from MySQL query with Python and lxml

I am trying to use Python and LXML to create an XML file from a Mysql query result. Here is the format I want.<DATA><ROW><FIELD1>content</FIELD1><FIELD2>content</FIELD2…

How to add another iterator to nested loop in python without additional loop?

I am trying to add a date to my nested loop without creating another loop. End is my list of dates and end(len) is equal to len(year). Alternatively I can add the date to the dataframe (data1) is that …