When creating a new image, the setting of the data type, and the overflow problem

When introducing the following bug, I want readers to think about a question first, whether the data type of the gray value in the digital map in opencv is np.int or np.uint8. When using opencv for image processing, numpy.zeros is used to create a pending image to be processed for spatial filtering. At first, it is thought that the category created by np.zeros is set to dtype=np.int. But after storing all the grayscale values ​​in the created matrix and displaying it with cv2.imshow, such an error occurs.

error: (-215:Assertion failed) src_depth != CV_16F && src_depth != CV_32S in function 'convertToShow'

The reason for the above error is: in the opencv library of python, the data type in image processing, or if an integer number is used to represent the gray value in a digital image, it is an unsigned 8-bit integer number, which is also It answers a question that made readers think at the beginning.

So when creating a matrix of image shape, dtype should be set to np.uint8

As follows:

new_image = np.zeros((high + 2 * p, width + 2 * p), dtype=np.uint8)

The dtype = np.uint8 of the created data type is preceded by the size of the image, which will not be introduced in detail here.

Another point is that for numpy.uint8, you need to know its range. According to the R, G, and B three-channel gray value range of the image, it is not difficult to speculate that the value range of numpy.uint8 is 0 to 255. For more than 255 If the value of numpy.uint is used for forced conversion, there will be an "overflow" scene, so that the final result is not what you expected.

The following is a brief introduction to the program:

import numpy as np
a = 256
b = np.uint8(a)
print(f"a - {a}, b - {b}")

The result of the operation is as follows:

According to the running results, if it exceeds 255, the final result will become 0. 

Although it is a small knowledge point, many bugs are prone to appear if you don't pay attention, so it is worth paying attention to.

Guess you like

Origin blog.csdn.net/kuwola/article/details/123357322