留作个人笔记,以供后需。
1. opencv只支持float32的图像显示和操作,然后float64是numpy的数据类型,opencv中不支持。在某些时候报错,需要将矩阵转为float32类型。
2. cv2.imread读出的图像为BGR模式而非RGB。
3. 图像uint8与float类型转换,uint8区间范围为0-255,而在对图片进行对比度增强,灰度等图片操作时,会引起图片像素值越界,因而在处理方法中还需要将图片矩阵像素值限制在规定范围内。虽然之前采用的方法是将图片写入存储中,之后再读取,我们可以看一下OpenCV 中imwrite函数对数据类型进行自动转换时,是根据如下的方法进行的:
Saturation Arithmetics
As a computer vision library, OpenCV deals a lot with image pixels that are often encoded in a compact, 8- or 16-bit per channel, form and thus have a limited value range. Furthermore, certain operations on images, like color space conversions, brightness/contrast adjustments, sharpening, complex interpolation (bi-cubic, Lanczos) can produce values out of the available range. If you just store the lowest 8 (16) bits of the result, this results in visual artifacts and may affect a further image analysis. To solve this problem, the so-called saturation arithmetics is used. For example, to store r, the result of an operation, to an 8-bit image, you find the nearest value within the 0..255 range:
Similar rules are applied to 8-bit signed, 16-bit signed and unsigned types. This semantics is used everywhere in the library. In C++ code, it is done using the saturate_cast<> functions that resemble standard C++ cast operations. See below the implementation of the formula provided above:
I.at<uchar>(y, x) = saturate_cast<uchar>(r);
where cv::uchar is an OpenCV 8-bit unsigned integer type. In the optimized SIMD code, such SSE2 instructions as paddusb, packuswb, and so on are used. They help achieve exactly the same behavior as in C++ code.
Note:
Saturation is not applied when the result is 32-bit integer.
而针对这个的替换处理方法使用numpy中的clip函数,将其限制在[0,255]范围内。
涉及参考:[bug] numpy.astype(uint8)和opencv imwrite函数的自动数据转换