PYTHON三种读取存入图像方法 VideoCapture读取视频两种方法 C++与PYTHON截图和缩放方法 waitKey Sleep sleep 图片文字putText

PYTHON三种方法

方法一、cv2

import cv2
filename=r’D:\Work\ILSVRC\val_3.jpeg’
im1=cv2.imread(filename) #读文件BGR格式
im1 = cv2.resize(im1,(400,400)) #默认双线性插值
#cv2.imshow(‘cv2’,im1) #显示图像, 在现在的petalinux生成的系统中和vitis ai的镜像中均不能使用cv2.imshow
#cv2.waitKey(0)

Syntax: cv2.imread(path, flag)
Parameters:
path: A string representing the path of the image to be read.
flag: It specifies the way in which image should be read. It’s default value is cv2.IMREAD_COLOR
Return Value: This method returns an image that is loaded from the specified file.

cv2.IMREAD_COLOR: It specifies to load a color image. Any transparency of image will be neglected. It is the default flag. Alternatively, we can pass integer value 1 for this flag.
cv2.IMREAD_GRAYSCALE: It specifies to load an image in grayscale mode. Alternatively, we can pass integer value 0 for this flag.
cv2.IMREAD_UNCHANGED: It specifies to load an image as such including alpha channel. Alternatively, we can pass integer value -1 for this flag.

cv::rectangle
C++
void cv::rectangle (InputOutputArray img, Point pt1, Point pt2, const Scalar &color, int thickness=1, int lineType=LINE_8, int shift=0)
void cv::rectangle (InputOutputArray img, Rect rec, const Scalar &color, int thickness=1, int lineType=LINE_8, int shift=0)

Python
img = cv.rectangle(img, pt1, pt2, color[, thickness[, lineType[, shift]]])
img = cv.rectangle(img, rec, color[, thickness[, lineType[, shift]]])

方法二、matplotlib plt

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
img2 = matplotlib.image.imread(pr)  #RGB格式
#cv2的BGR格式
plt.subplot(121)
plt.imshow(im2)
plt.show() #此命令才能显示

若是cv2.imread读取文件,plt显示需要转换
im1 = im1[:,:,::-1]  #BGR -> RGB

方法三、PIL

from PIL import Image
#import numpy as np
im2 = Image.open(filename) #不是矩阵形式
im2.show()
#arr = np.array(im2)
#print(arr.shape)
#print(arr.dtype)
#矩阵再转为图像
im3 = Image.fromarray(arr)
im3.save(‘01.png’)

OpenCV Show Image cvShowImage() 使用方法

新版的OpenCV在所有的函数和类前都加上了cv或Cv,这样很好的避免了区域污染(namespace pollution),而且不用在前面加‘cv::’,非常的使用。像之前的imshow()函数被现在的cvShowImage()所替代,现如今在OpenCV中显示一张图片可用如下代码:

C API:

IplImage *img = cvLoadImage(“Input.jpg”);
cvNamedWindow(“Image:”,1);
cvShowImage(“Image:”,img);
cvWaitKey();
cvDestroyWindow(“Image:”);
cvReleaseImage(&img);

C++:

cv::Mat image = cv::imread(“img.jpg”);
cv::namedWindow( “Display window”, cv::WINDOW_AUTOSIZE );
cv::imshow( “Display window”, image );
cv::waitKey(0);
cv::destroyWindow(“Display window”);
image.release();

C++版本截图实现

#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/core/core.hpp>
#include
using namespace std;
using namespace cv;
cv::Mat img;
cv::Rect m_select;
int main()
{
img = cv::imread(“F://Visual Studio 2015//ROItest01//ROItest01//01.jpg”);
cv::imshow(“原图”, img);
m_select = Rect(174,230,111,217);
Mat ROI = img(m_select);
cv::imshow(“剪裁图”, ROI);
waitKey(0);
return 0;
}

PYTHON版本截图实现

def central_crop(image, crop_height, crop_width):
image_height = image.shape[0]
image_width = image.shape[1]
offset_height = (image_height - crop_height) // 2
offset_width = (image_width - crop_width) // 2
return image[offset_height:offset_height + crop_height, offset_width:
offset_width + crop_width, :]

Python缩放图像

    cv2.namedWindow("Display", cv2.WINDOW_AUTOSIZE)
    cv2.moveWindow("Display",50,50)
    height, width = img.shape[:2]  
    size = (int(width*2), int(height*2))  
    image_result = cv2.resize(image_result, size, interpolation=cv2.INTER_LINEAR)  
    cv2.imshow("Display", image_result)
    if cv2.waitKey(2000)==27: 
       break       

waitKey()函数

1.1 waitKey()–这个函数是在一个给定的时间内(单位ms)等待用户按键触发;如果用户没有按下 键,则接续等待(循环)
1.2 如下所示: while(1){ if(waitKey(100)==27)break; } 在这个程序中,我们告诉OpenCv等待用户触发事件,等待时间为100ms,如果在这个时间段内, 用户按下ESC(ASCII码为27),则跳出循环,否则,则继续循环

Sleep sleep

#include <syswait.h>
usleep(n) //n微秒
Sleep(n)//n毫秒
sleep(n)//n秒

VideoCapture

1、cap = cv2.VideoCapture(0)
VideoCapture()中参数是0,表示打开笔记本的内置摄像头,参数是视频文件路径则打开视频,如cap = cv2.VideoCapture(“…/test.avi”)
2、ret,frame = cap.read()
cap.read()按帧读取视频,ret,frame是获cap.read()方法的两个返回值。其中ret是布尔值,如果读取帧是正确的则返回True,如果文件读取到结尾,它的返回值就为False。

C++

#include<opencv.hpp>
using namespace cv;
int main() {
    VideoCapture capture(0);

    while (1) {
        Mat frame;
        capture >> frame;

        imshow("摄像头捕捉", frame);

        waitKey(1);
    }
}
    Python有两种编程方式从摄像头提取视频流, video.capture(gstreamer pipeline), video.capture(index), 前者更灵活、更快、较复杂的调用方式,后者更简单、更容易实现的调用方式。video.capture(gstreamer pipeline),

video.capture(gstreamer pipeline)

# define the image
inputId = 'mediasrcbin media-device=/dev/media0 v4l2src0::io-mode=dmabuf v4l2src0::stride-align=256  ! video/x-raw, width=256, height=256, format=NV12, framerate=30/1 ! 
videoconvert! appsink’
# capture a video from camera
cam = cv2.VideoCapture(inputId, cv2.CAP_GSTREAMER)
# capture image from camera 
ret,frame = cam.read()

video.capture(gstreamer pipeline)

# capture a video from camera
cam = cv2.VideoCapture(1)    
# cam.set(3, width)
# cam.set(4, height)    cam.set(cv2.CAP_PROP_FRAME_WIDTH, 640)    cam.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
# capture image from camera 
ret,frame = cam.read() 
# resize the image
frame = cv2.resize(frame, (256, 256), interpolation=cv2.INTER_LINEAR)

图片文字

texts = [“wear mask”, “wear incorrectly”, “no mask”]
for i, bbox in enumerate(bboxes):
coor = np.array(bbox[:4], dtype=np.int32)
fontScale = 0.5
score = bbox[4]
class_ind = int(bbox[5])
#print(f"class_ind = {class_ind}")
bbox_color = colors[class_ind]
bbox_text = texts[class_ind]
#bbox_thick = int(0.6 * (image_h + image_w) / 600)
bbox_thick = 2
c1, c2 = (coor[0], coor[1]), (coor[2], coor[3])
cv2.rectangle(image, c1, c2, bbox_color, bbox_thick)
# 图片 添加的文字 位置 字体 字体大小 字体颜色 字体粗细
cv2.putText(image, bbox_text, (coor[0], coor[1]-10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, bbox_color, 2)

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值