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
BUG: uint16 inserted as int16 when assigning row with dict
It's expected the dtype is preserved - uint16 if possible, or an int which is large enough to represent the value. python : 3.8.10.final.0 python-bits : 64 OS : Linux machine : x86_64 pandas : 1.4.2 numpy : 1.22.4 pytz : 2022.1 dateutil : 2.8.2 pip : 20.0.2 setuptools : 44.0.0 Cython : None ... More on github.com
🌐 github.com
8
June 9, 2022
.net - How to use C# UInt16[,] in python - Stack Overflow
I am using clr to import c# dll in python one of the functions return ushort[,] , which is considered as System.UInt16[,] in python How can in convert System.UInt16[,] to numpy uint16 matrix? I c... 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)
🌐
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
🌐
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 ·
🌐
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-...
Find elsewhere
🌐
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.
🌐
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``).
🌐
Polars
docs.pola.rs › api › 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 ·
🌐
GitHub
github.com › pandas-dev › pandas › issues › 47294
BUG: uint16 inserted as int16 when assigning row with dict · Issue #47294 · pandas-dev/pandas
June 9, 2022 - It's expected the dtype is preserved - uint16 if possible, or an int which is large enough to represent the value. python : 3.8.10.final.0 python-bits : 64 OS : Linux machine : x86_64 pandas : 1.4.2 numpy : 1.22.4 pytz : 2022.1 dateutil : 2.8.2 pip : 20.0.2 setuptools : 44.0.0 Cython : None pytest : None hypothesis : None sphinx : None blosc : None feather : None xlsxwriter : None lxml.etree : None html5lib : None pymysql : None psycopg2 : None jinja2 : 3.1.2 IPython : None pandas_datareader: None bs4 : None bottleneck : None brotli : None fastparquet : None fsspec : None gcsfs : None markupsafe : 2.1.1 matplotlib : None numba : None numexpr : None odfpy : None openpyxl : None pandas_gbq : None pyarrow : None pyreadstat : None pyxlsb : None s3fs : None scipy : None snappy : None sqlalchemy : None tables : None tabulate : None xarray : None xlrd : None xlwt : None zstandard : None
Author   bluss
🌐
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]
🌐
GitHub
github.com › IntelRealSense › librealsense › issues › 12278
Capturing uint16 depth video using Python Script from Intel RealSense 435 Camera (Ubuntu 22.04) · Issue #12278 · IntelRealSense/librealsense
October 10, 2023 - How can I capture depth video in uint16 format (raw)? Currently, the following format sounds wrong (and the mkv depth video feels weird) import pyrealsense2 as rs import numpy as np import cv2 pipeline = rs.pipeline() config = rs.config(...
Author   monajalal