def flip_image(image, direction):
if direction == 'horizontal':
return image.transpose(Image.FLIP_LEFT_RIGHT)
elif direction == 'vertical':
return image.transpose(Image.FLIP_TOP_BOTTOM)
else:
print("Invalid direction! Use 'horizontal' or 'vertical'")
return image
The Python code you provided is a set of image processing functions using the Python Imaging Library (PIL), specifically Pillow, which is a fork of the original PIL that adds some user-friendly features and is actively maintained.
Here's a summary of the functions you've defined:
load_image: Loads an image from a given path.
convert_to_grayscale: Converts the image to grayscale.
crop_image: Crops the image to a specified size while keeping it centered.
rotate_image: Rotates the image by a given angle.
flip_image: Flips the image either horizontally or vertically.
smooth_image: Applies a smoothing filter to the image.
detect_edges: Detects the edges in the image using a filter.
Please note that there are a couple of places in the code that may need correction or improvement:
At the end of your provided code, you have a typo in the following line:
python
if __name__ == "main":
Instead, it should be:
python
if __name__ == "__main__":
This is necessary for the code inside the if block to execute when the script is run directly.
The img_path variable should have a correct file path that matches the location of the image file you want to process.
While calling .show(), remember that it will open the default image viewer on your system, and if you call multiple .show() one after another without closing the previous ones, it could be a bit messy depending on how your operating system handles multiple image windows.
Apart from these points, the supplied code should work well, provided you have the necessary image file at the location specified by img_path and that Pillow (PIL) is properly installed in your Python environment. To install Pillow, you can use pip:
bash
pip install Pillow
User
Sử dụng opencv và pyqt5
Đọc một ảnh
Chuyển đối sang ảnh xám
Cắt ảnh về kích thước cố định
Xoay ảnh, lật ảnh
Lọc, khử nhiễu cho ảnh
Phát hiện cạnh cho ảnh
Assistant
To accomplish these tasks using OpenCV (cv2) and PyQt5, you'll need to have both packages installed. You can install them with the following commands:
I'll provide you with a simple PyQt5 application that integrates OpenCV to perform the operations you've listed. The application will include a window with buttons to perform each transformation on the loaded image.
python
User
File "D:\Tailieuhoctap\thi giac may tinh\b1\main.py", line 85
start_row, start_col = int(h.25), int(w.25)
^^^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?
Assistant
Apologies for the confusion. The syntax error is due to the incorrect use of a period instead of an asterisk (*) to indicate multiplication for calculating the cropping dimensions. The correct syntax should include the multiplication symbol to take a percentage of the height and width, and then convert the results to integers. Here's the corrected code for the cropImage method:
python
def cropImage(self):
if self.image is not None:
h, w = self.image.shape[:2]
start_row, start_col = int(h * 0.25), int(w * 0.25)
end_row, end_col = int(h * 0.75), int(w * 0.75)
self.image = self.image[start_row:end_row, start_col:end_col]
self.displayImage()
Make sure to replace the incorrect h.25 and w.25 with h * 0.25 and w * 0.25 as shown above. This will calculate the start and end positions for cropping the image to its central 50% by width and height.
User
File "D:\Tailieuhoctap\thi giac may tinh\b1\main.py", line 3, in
from PyQt5.QtGui import QImage, QPixmap,QtCore
ImportError: cannot import name 'QtCore' from 'PyQt5.QtGui' (D:\Application\Python\Lib\site-packages\PyQt5\QtGui.pyd)
Assistant
The QtCore module should be imported from PyQt5, not from PyQt5.QtGui. As the error message states, there's no QtCore in the QtGui module. You need to adjust your import statements to correctly import QtCore from the base PyQt5 package and the other classes from their respective modules. Here's how you modify your imports:
python
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton, QLabel, QFileDialog, QVBoxLayout, QWidget)
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtCore import Qt # This is the correct import for QtCore
So for fixing your specific error, ensure that you change all occurrences of QtCore.Qt.SomeEnum to Qt.SomeEnum in your code after you've done the imports as shown above. If there's a direct reference to QtCore in your code, you will need to replace it with Qt.
Here's an example of how you'd use the corrected Qt import when scaling the image:
python
p = convert_to_Qt_format.scaled(640, 480, aspectRatioMode=Qt.KeepAspectRatio)
After the correction, the ImportError should be resolved, and the script should function as expected when run.
User
không chạy được
import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton, QLabel, QFileDialog, QVBoxLayout, QWidget)
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtCore import Qt
import cv2
class ImageProcessor(QMainWindow):
def init(self):
super().init()
code
Assistant
A few errors need to be corrected for the provided script to run properly.
The __init__ method is incorrectly named as init. It should have double underscores before and after the word init.
In the displayImage method, you must call the fromImage method on QPixmap correctly, like this: QPixmap.fromImage(p).
The if __name__ == 'main': condition is incorrect. It should have double underscores on both sides of the word main.
Here is the corrected version of your code:
python
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QLabel, QFileDialog, QVBoxLayout, QWidget
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtCore import Qt
import cv2
class ImageProcessor(QMainWindow):
def __init__(self): # Corrected this line
super().__init__()
self.image = None
self.initUI()
def initUI(self):
# ... (rest of your code for initUI)
def loadImage(self):
# ... (rest of your code for loadImage)
def displayImage(self, image=None):
if image is None:
image = self.image
frame = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
h, w, ch = frame.shape
bytes_per_line = ch * w
convert_to_Qt_format = QImage(frame.data, w, h, bytes_per_line, QImage.Format_RGB888)
p = convert_to_Qt_format.scaled(640, 480, aspectRatioMode=Qt.KeepAspectRatio)
self.imageLabel.setPixmap(QPixmap.fromImage(p)) # Corrected this line
def convertToGrayscale(self):
# ... (rest of your code for convertToGrayscale)
def cropImage(self):
# ... (rest of your code for cropImage)
def rotateImage(self):
# ... (rest of your code for rotateImage)
def flipImage(self):
# ... (rest of your code for flipImage)
def smoothImage(self):
# ... (rest of your code for smoothImage)
def detectEdges(self):
# ... (rest of your code for detectEdges)
def main():
app = QApplication(sys.argv)
ex = ImageProcessor()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__': # Corrected this line
main()
Make sure to replace your current code with the corrected version above. With these changes, the script should work as intended and allow you to process the image using OpenCV functions and display the results with a PyQt5 GUI.
User
self.imageLabel.setPixmap(QPixmap.fromImage§) § ? là cái gì
Assistant
The § symbol is a typographical error in the code snippet provided in my response. It should not be there. The correct line of code should be:
python
self.imageLabel.setPixmap(QPixmap.fromImage(p))
Here's what the displayImage method should look like after correction:
python
def displayImage(self, image=None):
if image is None:
image = self.image
if image is not None:
frame = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
h, w, ch = frame.shape
bytes_per_line = ch * w
convert_to_Qt_format = QImage(frame.data, w, h, bytes_per_line, QImage.Format_RGB888)
p = convert_to_Qt_format.scaled(640, 480, aspectRatioMode=Qt.KeepAspectRatio)
self.imageLabel.setPixmap(QPixmap.fromImage(p))
This method converts the supplied image into the RGB color space (which is what PyQt expects for display), creates a QImage from the data, scales it for display, and finally converts the QImage to a QPixmap which is then set to the QLabel for display. If no image is passed to the displayImage method, it displays the current image stored in the self.image attribute of the ImageProcessor class.
User
không mở pt5 lên được
import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton, QLabel, QFileDialog, QVBoxLayout, QWidget)
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtCore import Qt
import cv2
class ImageProcessor(QMainWindow):
def init(self):
super().init()
code
Assistant
The issue that you're encountering where PyQt5 does not launch correctly is due to another error in the if __name__ == 'main': condition. The correct syntax for this is if __name__ == '__main__':, with double underscores before and after main. Moreover, the __init__ method of the ImageProcessor class is again missing the double underscores.
Here's the corrected code part with the proper use of double underscores:
python
class ImageProcessor(QMainWindow):
def __init__(self): # Double underscores needed here
super().__init__()
self.image = None
self.initUI()
# ...
# ... (rest of your class code)
# ...
def main():
app = QApplication(sys.argv)
ex = ImageProcessor()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__': # Double underscores needed here
main()
Additionally, the line self.imageLabel.setPixmap(QPixmap.fromImage) needs to be changed to self.imageLabel.setPixmap(QPixmap.fromImage(p)). Here is the displayImage method with the corrected line:
python
def displayImage(self, image=None):
if image is None:
image = self.image
if image is not None:
frame = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
h, w, ch = frame.shape
bytes_per_line = ch * w
convert_to_Qt_format = QImage(frame.data, w, h, bytes_per_line, QImage.Format_RGB888)
p = convert_to_Qt_format.scaled(640, 480, aspectRatioMode=Qt.KeepAspectRatio)
self.imageLabel.setPixmap(QPixmap.fromImage(p)) # Corrected this line
Make sure you have corrected these issues in your code. After these corrections, your PyQt5 application should launch, and you should be able to load and process images using the GUI.
User
§??
Assistant
I apologize for the confusion. The "§" symbol mentioned in my previous response was a typographical error. It is not part of the Python code syntax and should not be included in your code.
The correct code for setting the QPixmap on the QLabel should be:
python
self.imageLabel.setPixmap(QPixmap.fromImage(p))
This line creates a QPixmap object from a QImage object (p) and sets it as the pixmap for self.imageLabel, which displays the image in the PyQt5 window.
Please ensure that you replace any stray "§" symbols with the correct code syntax before running your code. If you encounter any errors, please provide the exact error message, and I'll be happy to assist you further.
User
Sử dụng opencv và flask
Đọc một ảnh
Chuyển đối sang ảnh xám
Cắt ảnh về kích thước cố định
Xoay ảnh, lật ảnh
Lọc, khử nhiễu cho ảnh
Phát hiện cạnh cho ảnh
Assistant
To create a Flask application that uses OpenCV to perform various image processing tasks like reading an image, converting it to grayscale, cropping, rotating, flipping, smoothing (denoising), and edge detection, you can follow the steps below:
First, make sure you have Flask and OpenCV installed:
bash
pip install Flask opencv-python-headless
Now, you can write a Flask application that provides these functionalities. For simplicity, I'll create an application with endpoints that perform these operations individually. A production-ready app should include proper error handling and additional features like input validation.
Here's an example Flask application doing the required tasks:
import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton, QLabel, QFileDialog, QVBoxLayout, QWidget)
from PyQt5.QtGui import QImage, QPixmap
import cv2
class ImageProcessor(QMainWindow):
def __init__(self):
super().__init__()
self.image = None
self.initUI()
def initUI(self):
self.setWindowTitle('OpenCV with PyQt5')
layout = QVBoxLayout()
# Image display label
self.imageLabel = QLabel(self)
layout.addWidget(self.imageLabel)
# Button to load image
btnLoad = QPushButton('Load Image', self)
btnLoad.clicked.connect(self.loadImage)
layout.addWidget(btnLoad)
# Button to convert to grayscale
btnGray = QPushButton('Convert to Grayscale', self)
btnGray.clicked.connect(self.convertToGrayscale)
layout.addWidget(btnGray)
# Button to crop image
btnCrop = QPushButton('Crop Image', self)
btnCrop.clicked.connect(self.cropImage)
layout.addWidget(btnCrop)
# Button to rotate image
btnRotate = QPushButton('Rotate Image', self)
btnRotate.clicked.connect(self.rotateImage)
layout.addWidget(btnRotate)
# Button to flip image
btnFlip = QPushButton('Flip Image', self)
btnFlip.clicked.connect(self.flipImage)
layout.addWidget(btnFlip)
# Button to smooth image
btnSmooth = QPushButton('Smooth Image', self)
btnSmooth.clicked.connect(self.smoothImage)
layout.addWidget(btnSmooth)
# Button to detect edges
btnEdges = QPushButton('Detect Edges', self)
btnEdges.clicked.connect(self.detectEdges)
layout.addWidget(btnEdges)
# Set the layout on the application's window
container = QWidget()
container.setLayout(layout)
self.setCentralWidget(container)
def loadImage(self):
filename, _ = QFileDialog.getOpenFileName(self, 'Load Image', '', 'Image Files (*.png *.jpg *.bmp)')
if filename:
self.image = cv2.imread(filename)
self.displayImage()
def displayImage(self, image=None):
if image is None:
image = self.image
frame = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
h, w, ch = frame.shape
bytes_per_line = ch * w
convert_to_Qt_format = QImage(frame.data, w, h, bytes_per_line, QImage.Format_RGB888)
p = convert_to_Qt_format.scaled(640, 480, aspectRatioMode=QtCore.Qt.KeepAspectRatio)
self.imageLabel.setPixmap(QPixmap.fromImage(p))
def convertToGrayscale(self):
if self.image is not None:
self.image = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY)
self.displayImage()
def cropImage(self):
if self.image is not None:
h, w = self.image.shape[:2]
start_row, start_col = int(h*.25), int(w*.25)
end_row, end_col = int(h*.75), int(w*.75)
self.image = self.image[start_row:end_row, start_col:end_col]
self.displayImage()
def rotateImage(self):
if self.image is not None:
center = (self.image.shape[1] // 2, self.image.shape[0] // 2)
rotate_matrix = cv2.getRotationMatrix2D(center=center, angle=90, scale=1)
self.image = cv2.warpAffine(src=self.image, M=rotate_matrix, dsize=(self.image.shape[1], self.image.shape[0]))
self.displayImage()
def flipImage(self):
if self.image is not None:
self.image = cv2.flip(self.image, 1) # Horizontal flip
self.displayImage()
def smoothImage(self):
if self.image is not None:
self.image = cv2.GaussianBlur(self.image, (5, 5), 0)
self.displayImage()
def detectEdges(self):
if self.image is not None:
if len(self.image.shape) == 3 and self.image.shape[2] == 3:
# Convert to grayscale if it's a color image
gray = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY)
else:
gray = self.image
self.image = cv2.Canny(gray, 100, 200)
self.displayImage()
def main():
app = QApplication(sys.argv)
ex = ImageProcessor()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
This script defines a ImageProcessor class that extends QMainWindow and sets up a basic GUI layout with different buttons to perform the specified operations. The operations themselves utilize OpenCV functions for image processing, and the processed images are displayed using QLabel within the PyQt5 window.
Remember to run the GUI in the main thread by calling the main() function, which initializes a QApplication and displays the ImageProcessor window.
Keep in mind that the given crop method is a simple example that crops the central region of the image; you can adjust it according to your fixed size requirements. When operating on color images, some functions (like edge detection) convert the image to grayscale first since they are intended to work on single-channel images.
self.image = None
self.initUI()
def initUI(self):
self.setWindowTitle('OpenCV with PyQt5')
layout = QVBoxLayout()
# Image display label
self.imageLabel = QLabel(self)
layout.addWidget(self.imageLabel)
# Button to load image
btnLoad = QPushButton('Load Image', self)
btnLoad.clicked.connect(self.loadImage)
layout.addWidget(btnLoad)
# Button to convert to grayscale
btnGray = QPushButton('Convert to Grayscale', self)
btnGray.clicked.connect(self.convertToGrayscale)
layout.addWidget(btnGray)
# Button to crop image
btnCrop = QPushButton('Crop Image', self)
btnCrop.clicked.connect(self.cropImage)
layout.addWidget(btnCrop)
# Button to rotate image
btnRotate = QPushButton('Rotate Image', self)
btnRotate.clicked.connect(self.rotateImage)
layout.addWidget(btnRotate)
# Button to flip image
btnFlip = QPushButton('Flip Image', self)
btnFlip.clicked.connect(self.flipImage)
layout.addWidget(btnFlip)
# Button to smooth image
btnSmooth = QPushButton('Smooth Image', self)
btnSmooth.clicked.connect(self.smoothImage)
layout.addWidget(btnSmooth)
# Button to detect edges
btnEdges = QPushButton('Detect Edges', self)
btnEdges.clicked.connect(self.detectEdges)
layout.addWidget(btnEdges)
# Set the layout on the application's window
container = QWidget()
container.setLayout(layout)
self.setCentralWidget(container)
def loadImage(self):
filename, _ = QFileDialog.getOpenFileName(self, 'Load Image', '', 'Image Files (.png .jpg .bmp)')
if filename:
self.image = cv2.imread(filename)
self.displayImage()
def displayImage(self, image=None):
if image is None:
image = self.image
frame = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
h, w, ch = frame.shape
bytes_per_line = ch * w
convert_to_Qt_format = QImage(frame.data, w, h, bytes_per_line, QImage.Format_RGB888)
p = convert_to_Qt_format.scaled(640, 480, aspectRatioMode=Qt.KeepAspectRatio)
self.imageLabel.setPixmap(QPixmap.fromImage)
def convertToGrayscale(self):
if self.image is not None:
self.image = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY)
self.displayImage()
def cropImage(self):
if self.image is not None:
h, w = self.image.shape[:2]
start_row, start_col = int(h * 0.25), int(w * 0.25)
end_row, end_col = int(h * 0.75), int(w * 0.75)
self.image = self.image[start_row:end_row, start_col:end_col]
self.displayImage()
def rotateImage(self):
if self.image is not None:
center = (self.image.shape[1] // 2, self.image.shape[0] // 2)
rotate_matrix = cv2.getRotationMatrix2D(center=center, angle=90, scale=1)
self.image = cv2.warpAffine(src=self.image, M=rotate_matrix, dsize=(self.image.shape[1], self.image.shape[0]))
self.displayImage()
def flipImage(self):
if self.image is not None:
self.image = cv2.flip(self.image, 1) # Horizontal flip
self.displayImage()
def smoothImage(self):
if self.image is not None:
self.image = cv2.GaussianBlur(self.image, (5, 5), 0)
self.displayImage()
def detectEdges(self):
if self.image is not None:
if len(self.image.shape) == 3 and self.image.shape[2] == 3:
# Convert to grayscale if it's a color image
gray = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY)
else:
gray = self.image
self.image = cv2.Canny(gray, 100, 200)
self.displayImage()
def main():
app = QApplication(sys.argv)
ex = ImageProcessor()
ex.show()
sys.exit(app.exec_())
if name == 'main':
main()
self.image = None
self.initUI()
def initUI(self):
self.setWindowTitle('OpenCV with PyQt5')
layout = QVBoxLayout()
# Image display label
self.imageLabel = QLabel(self)
layout.addWidget(self.imageLabel)
# Button to load image
btnLoad = QPushButton('Load Image', self)
btnLoad.clicked.connect(self.loadImage)
layout.addWidget(btnLoad)
# Button to convert to grayscale
btnGray = QPushButton('Convert to Grayscale', self)
btnGray.clicked.connect(self.convertToGrayscale)
layout.addWidget(btnGray)
# Button to crop image
btnCrop = QPushButton('Crop Image', self)
btnCrop.clicked.connect(self.cropImage)
layout.addWidget(btnCrop)
# Button to rotate image
btnRotate = QPushButton('Rotate Image', self)
btnRotate.clicked.connect(self.rotateImage)
layout.addWidget(btnRotate)
# Button to flip image
btnFlip = QPushButton('Flip Image', self)
btnFlip.clicked.connect(self.flipImage)
layout.addWidget(btnFlip)
# Button to smooth image
btnSmooth = QPushButton('Smooth Image', self)
btnSmooth.clicked.connect(self.smoothImage)
layout.addWidget(btnSmooth)
# Button to detect edges
btnEdges = QPushButton('Detect Edges', self)
btnEdges.clicked.connect(self.detectEdges)
layout.addWidget(btnEdges)
# Set the layout on the application's window
container = QWidget()
container.setLayout(layout)
self.setCentralWidget(container)
def loadImage(self):
filename, _ = QFileDialog.getOpenFileName(self, 'Load Image', '', 'Image Files (.png .jpg .bmp)')
if filename:
self.image = cv2.imread(filename)
self.displayImage()
def displayImage(self, image=None):
if image is None:
image = self.image
if image is not None:
frame = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
h, w, ch = frame.shape
bytes_per_line = ch * w
convert_to_Qt_format = QImage(frame.data, w, h, bytes_per_line, QImage.Format_RGB888)
p = convert_to_Qt_format.scaled(640, 480, aspectRatioMode=Qt.KeepAspectRatio)
self.imageLabel.setPixmap(QPixmap.fromImage)
def convertToGrayscale(self):
if self.image is not None:
self.image = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY)
self.displayImage()
def cropImage(self):
if self.image is not None:
h, w = self.image.shape[:2]
start_row, start_col = int(h * 0.25), int(w * 0.25)
end_row, end_col = int(h * 0.75), int(w * 0.75)
self.image = self.image[start_row:end_row, start_col:end_col]
self.displayImage()
def rotateImage(self):
if self.image is not None:
center = (self.image.shape[1] // 2, self.image.shape[0] // 2)
rotate_matrix = cv2.getRotationMatrix2D(center=center, angle=90, scale=1)
self.image = cv2.warpAffine(src=self.image, M=rotate_matrix, dsize=(self.image.shape[1], self.image.shape[0]))
self.displayImage()
def flipImage(self):
if self.image is not None:
self.image = cv2.flip(self.image, 1) # Horizontal flip
self.displayImage()
def smoothImage(self):
if self.image is not None:
self.image = cv2.GaussianBlur(self.image, (5, 5), 0)
self.displayImage()
def detectEdges(self):
if self.image is not None:
if len(self.image.shape) == 3 and self.image.shape[2] == 3:
# Convert to grayscale if it's a color image
gray = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY)
else:
gray = self.image
self.image = cv2.Canny(gray, 100, 200)
self.displayImage()
def main():
app = QApplication(sys.argv)
ex = ImageProcessor()
ex.show()
sys.exit(app.exec_())
if name == 'main':
main()
from flask import Flask, request, send_file
import cv2
import numpy as np
from tempfile import NamedTemporaryFile
app = Flask(__name__)
@app.route('/read-image', methods=['POST'])
def read_image():
if 'file' not in request.files:
return "No file part", 400
file = request.files['file']
if file.filename == '':
return "No selected file", 400
image = cv2.imdecode(np.fromstring(file.read(), np.uint8), cv2.IMREAD_UNCHANGED)
return process_image(image)
@app.route('/convert-to-grayscale', methods=['POST'])
def convert_to_grayscale():
image = get_image_from_request(request)
grayscale_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
return process_image(grayscale_image)
@app.route('/crop-image', methods=['POST'])
def crop_image():
image = get_image_from_request(request)
h, w = image.shape[:2]
cropped_image = image[h//4:h*3//4, w//4:w*3//4]
return process_image(cropped_image)
@app.route('/rotate-image', methods=['POST'])
def rotate_image():
image = get_image_from_request(request)
angle = request.form.get("angle", default=0, type=int)
rotate_matrix = cv2.getRotationMatrix2D(center=(w / 2, h / 2), angle=angle, scale=1)
rotated_image = cv2.warpAffine(image, rotate_matrix, (w, h))
return process_image(rotated_image)
@app.route('/flip-image', methods=['POST'])
def flip_image():
image = get_image_from_request(request)
flip_mode = request.form.get("mode", default=1, type=int) # 0 for vertical, 1 for horizontal flip
flipped_image = cv2.flip(image, flip_mode)
return process_image(flipped_image)
@app.route('/smooth-image', methods=['POST'])
def smooth_image():
image = get_image_from_request(request)
smooth_image = cv2.GaussianBlur(image, (5, 5), 0)
return process_image(smooth_image)
@app.route('/detect-edges', methods=['POST'])
def detect_edges():
image = get_image_from_request(request)
edges_image = cv2.Canny(image, 100, 200)
return process_image(edges_image)
def get_image_from_request(request):
if 'file' not in request.files:
raise ValueError("No file part")
file = request.files['file']
if file.filename == '':
raise ValueError("No selected file")
image = cv2.imdecode(np.fromstring(file.read(), np.uint8), cv2.IMREAD_UNCHANGED)
return image
def process_image(image):
is_success, buffer = cv2.imencode(".jpg", image)
if not is_success:
return "Could not process image", 500
with NamedTemporaryFile(delete=False) as temp_file:
temp_file.write(buffer)
temp_file.flush()
return send_file(temp_file.name, mimetype='image/jpeg', as_attachment=True)
if __name__ == '__main__':
app.run(debug=True)
In the code above, each endpoint performs a specific operation on the uploaded image and then sends the processed image back as a response. The get_image_from_request function extracts the image data from the incoming request, and process_image converts the OpenCV image back into a JPEG to be returned in the HTTP response.
To use these endpoints, you would send a POST request to the desired endpoint with the image file included in the request. For example, to convert an image to grayscale, you would POST the image file to /convert-to-grayscale.
Keep in mind that for simplicity, I'm using NamedTemporaryFile to temporarily store the processed image file to send it as a response. In a production environment, it's better to use more persistent and secure methods for handling files.