用OPencv写出图片resize,转换成rgb模式,像素值标准化的代码
时间: 2024-05-12 20:17:27 浏览: 13
以下是使用OpenCV进行图片resize、转换成RGB模式和像素值标准化的代码示例:
```python
import cv2
import numpy as np
# 读取图片
img = cv2.imread('example.jpg')
# 图片resize
img_resized = cv2.resize(img, (224, 224))
# 转换成RGB模式
img_rgb = cv2.cvtColor(img_resized, cv2.COLOR_BGR2RGB)
# 像素值标准化
img_norm = img_rgb.astype(np.float32) / 255.0
```
这里使用了OpenCV中的`cv2.imread()`函数读取图片,`cv2.resize()`函数进行resize操作,`cv2.cvtColor()`函数进行色彩空间转换,最后使用了numpy中的`astype()`函数将像素值转换为浮点数,并除以255进行标准化。
相关问题
opencv中全部显示图片的像素值的操作,并写出代码
要显示图片的全部像素值,可以使用OpenCV中的`cv::Mat`类及其`cv::imshow`函数。以下是一段示例代码:
```c++
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
Mat img = imread("path/to/your/image.jpg"); // 读取图片
if (img.empty()) // 判断是否读取成功
{
cout << "Failed to read image!" << endl;
return -1;
}
// 将所有像素值转成字符串并拼接成一个长字符串
string pixel_values = "";
for (int i = 0; i < img.rows; i++)
{
for (int j = 0; j < img.cols; j++)
{
Vec3b pixel = img.at<Vec3b>(i, j);
pixel_values += to_string(pixel[0]) + "," + to_string(pixel[1]) + "," + to_string(pixel[2]) + "; ";
}
pixel_values += "\n";
}
cout << pixel_values << endl; // 输出像素值字符串
imshow("Image", img); // 显示图片
waitKey(0); // 等待按键
return 0;
}
```
在上面的代码中,我们读取了一张图片并将每个像素的RGB值转成字符串,并拼接成一个长字符串。然后我们输出这个字符串,并使用OpenCV的`cv::imshow`函数显示原图。需要注意的是,`cv::imshow`函数只能显示8位或16位的单通道、三通道或四通道图像,如果图片不是这种格式的话需要先进行转换。另外,使用`cv::imshow`函数时需要在程序中包含`#include <opencv2/highgui.hpp>`。
openCV中显示灰度图片的像素值的操作,并写出代码
要显示灰度图片的像素值,可以使用OpenCV中的`cv::Mat`类及其`cv::imshow`函数。以下是一段示例代码:
```c++
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
Mat img = imread("path/to/your/image.jpg", IMREAD_GRAYSCALE); // 以灰度模式读取图片
if (img.empty()) // 判断是否读取成功
{
cout << "Failed to read image!" << endl;
return -1;
}
// 将所有像素值转成字符串并拼接成一个长字符串
string pixel_values = "";
for (int i = 0; i < img.rows; i++)
{
for (int j = 0; j < img.cols; j++)
{
uchar pixel = img.at<uchar>(i, j);
pixel_values += to_string(pixel) + "; ";
}
pixel_values += "\n";
}
cout << pixel_values << endl; // 输出像素值字符串
imshow("Image", img); // 显示图片
waitKey(0); // 等待按键
return 0;
}
```
在上面的代码中,我们读取了一张灰度图片并将每个像素的灰度值转成字符串,并拼接成一个长字符串。然后我们输出这个字符串,并使用OpenCV的`cv::imshow`函数显示灰度图像。需要注意的是,使用`cv::imshow`函数显示灰度图像时,只需要读取灰度图像并将其作为单通道图像显示即可。