def scale_image(image, scale): width = int(image.shape[1] * scale) height = int(image.shape[0] * scale) return cv2.resize(image, (width, height))
时间: 2023-10-30 10:04:40 浏览: 33
这是一个 Python 函数,用于将图像按比例缩放。参数 image 是输入的图像,scale 是缩放比例。该函数使用 OpenCV 库中的 cv2.resize 函数进行缩放操作。首先,函数通过 image.shape 获取输入图像的宽度和高度,然后计算出缩放后的宽度和高度。最后,使用 cv2.resize 函数将图像按比例缩放到新的尺寸。函数返回缩放后的图像。
相关问题
import cv2 # 初始化背景建模器 fgbg = cv2.createBackgroundSubtractorMOG2() # 读取视频文件 cap = cv2.VideoCapture('w5.mp4') while True: # 读取一帧图像 ret, frame = cap.read() if not ret: break # 对图像进行背景建模 fgmask = fgbg.apply(frame) # 缩放比例 scale_percent = 50 # 计算缩放后的新尺寸 width = int(frame.shape[1] * scale_percent / 100) height = int(frame.shape[0] * scale_percent / 100) dim = (width, height) # 缩放图像 frame = cv2.resize(frame, dim, interpolation=cv2.INTER_AREA) fgmask = cv2.resize(fgmask, dim, interpolation=cv2.INTER_AREA) # 对二值化结果进行形态学操作 kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)) fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel) # 寻找轮廓并绘制矩形框 contours, hierarchy = cv2.findContours(fgmask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for contour in contours: area = cv2.contourArea(contour) if area > 1500: # 去除过小的噪点 x, y, w, h = cv2.boundingRect(contour) cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2) # 显示结果 cv2.imshow('frame', frame) cv2.imshow('fgmask', fgmask) if cv2.waitKey(30) == ord('q'): break # 释放资源 cap.release() cv2.destroyAllWindows()用pyqt5帮这个程序做一个可视化界面
可以使用PyQt5来实现可视化界面,以下是一个简单的示例代码:
```python
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QVBoxLayout
import cv2
import numpy as np
class VideoPlayer(QWidget):
def __init__(self):
super().__init__()
# 初始化背景建模器
self.fgbg = cv2.createBackgroundSubtractorMOG2()
# 创建界面元素
self.label = QLabel(self)
self.button = QPushButton('开始/暂停', self)
self.button.clicked.connect(self.toggle_playback)
# 创建布局并添加元素
layout = QVBoxLayout()
layout.addWidget(self.label)
layout.addWidget(self.button)
self.setLayout(layout)
# 初始化视频播放状态
self.playing = False
# 读取视频文件
self.cap = cv2.VideoCapture('w5.mp4')
# 启动定时器
self.timer = self.startTimer(30)
def toggle_playback(self):
self.playing = not self.playing
def timerEvent(self, event):
if self.playing:
# 读取一帧图像
ret, frame = self.cap.read()
if not ret:
# 视频播放结束
self.playing = False
self.cap.release()
cv2.destroyAllWindows()
return
# 对图像进行背景建模
fgmask = self.fgbg.apply(frame)
# 缩放比例
scale_percent = 50
# 计算缩放后的新尺寸
width = int(frame.shape[1] * scale_percent / 100)
height = int(frame.shape[0] * scale_percent / 100)
dim = (width, height)
# 缩放图像
frame = cv2.resize(frame, dim, interpolation=cv2.INTER_AREA)
fgmask = cv2.resize(fgmask, dim, interpolation=cv2.INTER_AREA)
# 对二值化结果进行形态学操作
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel)
# 寻找轮廓并绘制矩形框
contours, hierarchy = cv2.findContours(fgmask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
area = cv2.contourArea(contour)
if area > 1500: # 去除过小的噪点
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
# 将图像转换为RGB格式并显示
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
image = np.rot90(frame)
height, width, channel = image.shape
bytesPerLine = 3 * width
qImg = QImage(image.data, width, height, bytesPerLine, QImage.Format_RGB888)
self.label.setPixmap(QPixmap.fromImage(qImg))
if __name__ == '__main__':
app = QApplication(sys.argv)
player = VideoPlayer()
player.show()
sys.exit(app.exec_())
```
这个程序中,我们创建了一个名为 `VideoPlayer` 的类,继承自 `QWidget`,并包含一个标签和一个按钮。在类的初始化方法中,我们创建了这些界面元素,并将它们添加到一个垂直布局中。我们还初始化了视频播放状态和定时器,并在定时器回调函数中读取视频帧、进行背景建模、绘制矩形框等处理,并将处理后的图像显示在标签中。在按钮的点击事件中,我们切换视频播放状态。最后,我们使用 `QApplication` 启动了程序,并显示了 `VideoPlayer` 窗口。
注意:在运行程序之前,需要确保已经正确安装了 PyQt5 和 OpenCV。
import cv2 import numpy as np # 读取原始图像 img = cv2.imread('image.webp') # 缩放变换 scale_percent = 50 # 缩放比例 width = int(img.shape[1] * scale_percent / 100) # 新图像宽度 height = int(img.shape[0] * scale_percent / 100) # 新图像高度 dim = (width, height) resized = cv2.resize(img, dim, interpolation = cv2.INTER_AREA) # 旋转变换 angle = 45 # 旋转角度 rotation_matrix = cv2.getRotationMatrix2D((img.shape[1]/2, img.shape[0]/2), angle, 1) rotated = cv2.warpAffine(img, rotation_matrix, (img.shape[1], img.shape[0])) # 平移变换 x = 50 # 水平方向平移像素数 y = 100 # 垂直方向平移像素数 translation_matrix = np.float32([[1, 0, x], [0, 1, y]]) translated = cv2.warpAffine(img, translation_matrix, (img.shape[1], img.shape[0])) # 裁剪变换 x1 = 100 # 左上角横坐标 y1 = 100 # 左上角纵坐标 x2 = 300 # 右下角横坐标 y2 = 300 # 右下角纵坐标 cropped = img[y1:y2, x1:x2] # 镜像变换 mirrored = cv2.flip(img, 1) # 在同一个窗口内分成六个子窗口来分别显示原图和变换后的图像 cv2.namedWindow('Image', cv2.WINDOW_NORMAL) cv2.resizeWindow('Image', 700, 700) cv2.imshow('Image', np.vstack((img, resized, rotated, translated, cropped, mirrored))) cv2.waitKey(0) cv2.destroyAllWindows()优化这段代码,并显示结果图
可以将这段代码封装成一个函数,并将变换操作作为参数传递给函数,以避免代码重复。以下是一个示例:
```python
import cv2
import numpy as np
def apply_transformations(img, transformations):
transformed_images = []
for transformation in transformations:
if transformation == 'resize':
scale_percent = 50
width = int(img.shape[1] * scale_percent / 100)
height = int(img.shape[0] * scale_percent / 100)
dim = (width, height)
resized = cv2.resize(img, dim, interpolation=cv2.INTER_AREA)
transformed_images.append(resized)
elif transformation == 'rotate':
angle = 45
rotation_matrix = cv2.getRotationMatrix2D((img.shape[1]/2, img.shape[0]/2), angle, 1)
rotated = cv2.warpAffine(img, rotation_matrix, (img.shape[1], img.shape[0]))
transformed_images.append(rotated)
elif transformation == 'translate':
x = 50
y = 100
translation_matrix = np.float32([[1, 0, x], [0, 1, y]])
translated = cv2.warpAffine(img, translation_matrix, (img.shape[1], img.shape[0]))
transformed_images.append(translated)
elif transformation == 'crop':
x1 = 100
y1 = 100
x2 = 300
y2 = 300
cropped = img[y1:y2, x1:x2]
transformed_images.append(cropped)
elif transformation == 'mirror':
mirrored = cv2.flip(img, 1)
transformed_images.append(mirrored)
return transformed_images
# 读取原始图像
img = cv2.imread('image.webp')
# 定义要应用的变换
transformations = ['resize', 'rotate', 'translate', 'crop', 'mirror']
# 应用变换并显示结果图像
transformed_images = apply_transformations(img, transformations)
cv2.namedWindow('Transformed Images', cv2.WINDOW_NORMAL)
cv2.resizeWindow('Transformed Images', 1200, 800)
cv2.imshow('Transformed Images', np.hstack(transformed_images))
cv2.waitKey(0)
cv2.destroyAllWindows()
```
这个函数将原始图像和要应用的变换作为参数,返回一个包含所有变换后图像的列表。通过调用这个函数并将返回的结果合并成一张图像,就可以显示所有变换后的图像。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)