Dtypes don't work like they look at first glance. np.uint16 isn't a dtype object. It's just convertible to one. np.uint16 is a type object representing the type of array scalars of uint16 dtype.

x.dtype is an actual dtype object, and dtype objects implement == in a weird way that's non-transitive and inconsistent with hash. dtype == other is basically implemented as dtype == np.dtype(other) when other isn't already a dtype. You can see the details in the source.

Particularly, x.dtype compares equal to np.uint16, but it doesn't have the same hash, so the dict lookup doesn't find it.

Answer from user2357112 on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › declaring an unsigned integer 16 in python for bit shift operation
r/learnpython on Reddit: Declaring an Unsigned Integer 16 in Python for Bit Shift Operation
October 29, 2023 -

SOLVED: 3 Solutions:

  1. using Numpy : np.uint16()

  2. Using CTypes : ctypes.c_uint16()

  3. Using Bitwise : & 0xFFFF


Hi, I'm trying to convert this code to Python from Go / C. It involves declaring a UInt16 variable and run a bit shift operation. However cant seem to create a variable with this specific type. Need some advise here.

Go Code:

package main

import "fmt"

func main() {

var dx uint16 = 38629

var dy uint16 = dx << 8

fmt.Println(dy) //58624 -> Correct value

}

Python Code:

dx = 38629

dy = (dx << 8)

print(dy) # 9889024 -> not the expected value

print(type(dx)) # <class 'int'>

print(type(dy)) # <class 'int'>

I cant seem to figure out a way to cast or similar function to get this into an Unsigned Int 16.\

Please help.

Discussions

Newest 'uint16' Questions - Stack Overflow
I am creating a python OPC UA client based on opcua-asyncio github (https://github.com/FreeOpcUa/opcua-asyncio) to read values in an instrument that has a server already set up. My problem lies in ... ... I am trying to register two 16bit images. One is a .dcm CT series and the other is TIFF image. Both are uint16 ... More on stackoverflow.com
🌐 stackoverflow.com
python - float to uint16 conversion blowing numbers up in numpy? - Stack Overflow
My data has daily indates from 1947 to 2012 and outdates from 1997 to 2012. I do not understand how the lines below could result in a monthstoadd = 62844 (which blow some time offsets up). Can it b... More on stackoverflow.com
🌐 stackoverflow.com
Python Unsigned 16-bit Integer Array Elements - Stack Overflow
I'm trying to build the equivalent of the buffer of a Javascript Uint16Array object: Uint16Array(someArray).buffer). More on stackoverflow.com
🌐 stackoverflow.com
c - how to unpack a struct with uint16_t type in python - Stack Overflow
I'm trying to unpack ElfHeader in python. Type of e_type in Elf64_Edhr struct is uint16_t, How can I unpack it? I only found a way to unpack 4 bit unsigned int in python struct docs. More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 1
4

Your data corruption is caused by integer overflow.

Once a numpy integer goes outside the range of a datatype (0-255 for uint8), the value overflows and wraps around to 0 again.

For example:

np.uint16(255).astype(np.uint8) == 255
np.uint16(256).astype(np.uint8) == 0
np.uint16(258).astype(np.uint8) == 2
np.uint16(260).astype(np.uint8) == 4
np.uint16(511).astype(np.uint8) == 255
np.uint16(512).astype(np.uint8) == 0
np.uint16(514).astype(np.uint8) == 2
np.uint16(516).astype(np.uint8) == 4

A simple rescale will work, e.g.

data_8bit = ((data - data.min()) / (data.max() - data.min()) * 255).astype(np.uint8)

But you'll get a much nicer looking image if you rescale per band and even better with a per band percentile stretch similar to what most GIS software does, such as [2, 98] or [1, 99]. E.g.

import rasterio
import numpy as np

input_tiff = "test_uint16.tif"
output_tiff = "test_uint8.tif"

percentiles = [1, 99]

with rasterio.open(input_tiff) as src:
    profile = src.profile
    profile.update(dtype=rasterio.uint8)

    with rasterio.open(output_tiff, 'w', **profile) as dst:
        for i in range(src.count):
            band = i+1
            data = src.read(band, masked=True)

            # data.compressed() returns an array of non-masked pixel values
            pmin, pmax = np.percentile(data.compressed(), percentiles)

            # rescale 0-1
            data = (data - pmin) / (pmax - pmin)

            # Ensure data is >= pmin <= pmax
            data[data<0] = 0
            data[data>1] = 1

            # Make it 0-255 8bit unsigned.
            data_int8 = (data * 255).astype(np.uint8)

            dst.write(data_int8, band)
🌐
Readthedocs
iec104-python.readthedocs.io › latest › python › number › uint16.html
Usigned Integer (16-bit) — iec104-python 2.2 documentation
c104 python module · Number · Usigned Integer (16-bit) View page source · class c104.UInt16 · __init__(self, value: int) → None · create a fixed-length integer instance · Parameters: value (int) – the value · Raises: ValueError – cannot convert value to fixed-length integer ·
🌐
ProgramCreek
programcreek.com › python › example › 8189 › numpy.uint16
Python Examples of numpy.uint16
def ordinal2yeardoy(ordinal): """ Convert ordinal dates to two arrays of year and doy Args: ordinal (np.ndarray): ordinal dates Returns: np.ndarray: nobs x 2 np.ndarray containing the year and DOY for each ordinal date """ _date = [dt.fromordinal(_d) for _d in ordinal] yeardoy = np.empty((ordinal.size, 2), dtype=np.uint16) yeardoy[:, 0] = np.array([int(_d.strftime('%Y')) for _d in _date]) yeardoy[:, 1] = np.array([int(_d.strftime('%j')) for _d in _date]) return yeardoy
🌐
Python Data Science Handbook
jakevdp.github.io › PythonDataScienceHandbook › 02.01-understanding-data-types.html
Understanding Data Types in Python | Python Data Science Handbook
The standard Python implementation is written in C. This means that every Python object is simply a cleverly-disguised C structure, which contains not only its value, but other information as well. For example, when we define an integer in Python, such as x = 10000, x is not just a "raw" integer.
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › tagged › uint16
Newest 'uint16' Questions - Stack Overflow
I am creating a python OPC UA client based on opcua-asyncio github (https://github.com/FreeOpcUa/opcua-asyncio) to read values in an instrument that has a server already set up. My problem lies in ... ... I am trying to register two 16bit images. One is a .dcm CT series and the other is TIFF image. Both are uint16 type and while running SIFT I get this error: cv2.error: OpenCV(4.8.0) D:\a\opencv-...
🌐
Polars
docs.pola.rs › docs › python › dev › reference › api › polars.datatypes.UInt16.html
polars.datatypes.UInt16 — Polars documentation
class polars.datatypes.UInt16[source]# 16-bit unsigned integer type. __init__(*args, **kwargs)# Methods ·
🌐
Snyk
snyk.io › advisor › nptyping › functions › nptyping.int16
How to use the nptyping.Int16 function in nptyping | Snyk
def test_get_type_numpy_dtype(self): self.assertEqual(Int8, get_type(np.int8(42))) self.assertEqual(Int16, get_type(np.int16(42))) self.assertEqual(Int32, get_type(np.int32(42))) self.assertEqual(Int64, get_type(np.int64(42))) self.assertEqual(UInt8, get_type(np.uint8(42))) self.assertEqual(UInt16, get_type(np.uint16(42))) self.assertEqual(UInt32, get_type(np.uint32(42))) self.assertEqual(UInt64, get_type(np.uint64(42))) self.assertEqual(Float16, get_type(np.float16(42.0))) self.assertEqual(Float32, get_type(np.float32(42.0))) self.assertEqual(Float64, get_type(np.float64(42.0))) self.assertEqual(Unicode, get_type(np.unicode)) self.assertEqual(Unicode[40], get_type(np.dtype(('U', 40)))) self.assertEqual(Bool, get_type(np.bool_(True))) ramonhagenaars / nptyping / tests / test_functions / test_get_type.py View on Github ·
🌐
KooR.fr
koor.fr › Python › API › scientist › numpy › uint16 › Index.wp
KooR.fr - classe uint16 - module numpy - Description de quelques librairies Python
Unsigned integer type, compatible with C ``unsigned short``. :Character code: ``'H'`` :Canonical name: `numpy.ushort` :Alias on this platform (win32 AMD64): `numpy.uint16`: 16-bit unsigned integer (``0`` to ``65_535``).
🌐
Stack Overflow
stackoverflow.com › questions › 72563282 › how-to-use-c-sharp-uint16-in-python
.net - How to use C# UInt16[,] in python - Stack Overflow
import clr import os import numpy as np dll_name = os.path.join(os.path.abspath(os.path.dirname(__file__)), ("mydll") + ".dll") clr.AddReference(dll_name) from mynamespace import myclass myobject = myclass() numpy_matrix = np.empty([80,260],dtype = np.uint16) SystemInt16_matrix = myobject.Getdata() for i in range(20): for j in range(32): numpy_matrix[i,j]=SystemInt16_matrix[i,j]