图片RGB转BGR——基于python+opencv+vscode

最近利用ESP32外接驱动为ST7789、分辨率为320*240的2寸TFT显示屏,发现颜色出现了混乱,让其显示一张RGB图片实际显示为BGR图片:

                               原RGB图                                                 实际显示图(BGR)

网上查阅各种办法改了各种头文件还是解决不了,调什么颜色翻转参数、宏定义什么TFT_BGR之类的都不行,估计和opencv一样读取图片时是由低字节向高字节读导致的,其默认的像素排列为BGR。/真的抽象.jpg /真的苦涩.jpg

索性抽象就按抽象着来,咱自己把图片转换为BGR像素排列的不就行了!

基于电脑上已经安装了vscode,而且安装了python环境,网上查阅opencv可以使用自带的函数将图片的R色和B色调转,Win+R cmd输入pip install opencv-python直接安装opencv的环境就行:

1、安装vscode Visual Studio Code - Code Editing. Redefined

2、安装python 超详细的Python安装和环境搭建教程_python安装教程-优快云博客

3、安装opencv环境  Win+R cmd输入pip install opencv-python

        等待几分钟,安装完成后会打印出Successfully installed opencv-python-xxx的信息,然后命令行输入python,再输入import cv2未报错则为安装成功。

利用vscode运行demo.py程序:

安装好的opencv会被保存在python安装文件夹中Lib文件夹下面的site-packages文件夹中。

python安装的文件夹位置:Win+R cmd输入python,输入import sys,再输入sys.path会打印出python安装文件夹的位置,大概为C:\Users\lenovo\AppData\Local\Programs\Python\Python311

然后在site-packages文件夹下找到cv2文件夹,找到cv2.pyd程序,复制一份拷贝到桌面上的一个新建文件夹里,新建文件夹用英文命名。

在这个文件夹里再新建一个txt文本文件,重命名为demo.py,用记事本打开后输入以下代码然后保存,同时也把你待转换的RGB图放进文件夹中:

  

import numpy as np
import cv2

img = cv2.imread("picture.jpg")
img_bgr = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
cv2.namedWindow('img_bgr',cv2.WINDOW_AUTOSIZE)
cv2.imshow('imgwindow',img_bgr)
cv2.imwrite('img.jpg',img_bgr)
cv2.waitKey(0)

picture.jpg替换为你的图片名,cv2.imread为读取图片,cv2.cvtColor带cv2.COLOR_RGB2BGR参数为转为BGR图片,cv2.imwrite为保存图片,cv2.waitKey()为等待按键。

然后打开vscode,左上角 文件—打开文件夹—选择桌面上刚才新建的文件夹,然后点右上角的三角图标(运行python文件)

最终在弹出的窗口imgwindow中会显示转换后的BGR图片,并且在文件夹下会生成名为img.jpg的BGR图片。

                              

之后将该BGR图片再用TFT屏幕显示,不出所料显示正常了。。。

为了帮助你完成基于PythonOpenCV的图像处理软件项目,我将为你提供一个基本的框架代码。这个框架将涵盖文档中提到的主要功能。你可以根据具体需求进一步扩展和完善这些功能。 ### 项目结构 ``` image_processor/ │ ├── main.py ├── image_utils.py ├── gui.py └── README.md ``` ### 1. `main.py` - 主程序入口 ```python import tkinter as tk from tkinter import filedialog, messagebox import cv2 import numpy as np from PIL import Image, ImageTk from image_utils import ImageProcessor from gui import Application def main(): root = tk.Tk() app = Application(root) root.mainloop() if __name__ == "__main__": main() ``` ### 2. `image_utils.py` - 图像处理工具 ```python import cv2 import numpy as np class ImageProcessor: def __init__(self): self.image = None def load_image(self, path): self.image = cv2.imread(path) return self.image def save_image(self, path, format=None): if format: cv2.imwrite(path, self.image, [int(cv2.IMWRITE_JPEG_QUALITY), 90]) else: cv2.imwrite(path, self.image) def resize_image(self, width, height): self.image = cv2.resize(self.image, (width, height)) def rotate_image(self, angle): (h, w) = self.image.shape[:2] center = (w // 2, h // 2) M = cv2.getRotationMatrix2D(center, angle, 1.0) self.image = cv2.warpAffine(self.image, M, (w, h)) def crop_image(self, x, y, width, height): self.image = self.image[y:y+height, x:x+width] def adjust_brightness(self, value): hsv = cv2.cvtColor(self.image, cv2.COLOR_BGR2HSV) h, s, v = cv2.split(hsv) lim = 255 - value v[v > lim] = 255 v[v <= lim] += value final_hsv = cv2.merge((h, s, v)) self.image = cv2.cvtColor(final_hsv, cv2.COLOR_HSV2BGR) def adjust_contrast(self, value): alpha = float(131 * (value + 127)) / (127 * (131 - value)) gamma = 127 * (1 - alpha) self.image = cv2.addWeighted(self.image, alpha, self.image, 0, gamma) def auto_correct(self): # Simple auto-correction using CLAHE lab = cv2.cvtColor(self.image, cv2.COLOR_BGR2LAB) l, a, b = cv2.split(lab) clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8, 8)) cl = clahe.apply(l) limg = cv2.merge((cl, a, b)) self.image = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR) def draw_histogram(self): hist = cv2.calcHist([self.image], [0], None, [256], [0, 256]) return hist def compress_image(self, quality): _, encoded_image = cv2.imencode('.jpg', self.image, [int(cv2.IMWRITE_JPEG_QUALITY), quality]) self.image = cv2.imdecode(encoded_image, 1) def get_image_info(self): return { "filename": "example.jpg", "file_size": self.image.nbytes, "dimensions": self.image.shape[:2], "position": (0, 0) } ``` ### 3. `gui.py` - 图形用户界面 ```python import tkinter as tk from tkinter import filedialog, messagebox from PIL import Image, ImageTk from image_utils import ImageProcessor class Application: def __init__(self, master): self.master = master self.master.title("Python Image Processor") self.processor = ImageProcessor() self.image_label = tk.Label(master) self.image_label.pack() self.menu = tk.Menu(master) self.master.config(menu=self.menu) file_menu = tk.Menu(self.menu, tearoff=0) self.menu.add_cascade(label="File", menu=file_menu) file_menu.add_command(label="Open", command=self.open_image) file_menu.add_command(label="Save", command=self.save_image) file_menu.add_command(label="Save As", command=self.save_image_as) file_menu.add_command(label="Rename", command=self.rename_image) file_menu.add_command(label="Clear", command=self.clear_image) file_menu.add_command(label="Exit", command=self.master.quit) edit_menu = tk.Menu(self.menu, tearoff=0) self.menu.add_cascade(label="Edit", menu=edit_menu) edit_menu.add_command(label="Zoom In", command=self.zoom_in) edit_menu.add_command(label="Zoom Out", command=self.zoom_out) edit_menu.add_command(label="Rotate Left", command=lambda: self.rotate_image(90)) edit_menu.add_command(label="Rotate Right", command=lambda: self.rotate_image(-90)) edit_menu.add_command(label="Crop", command=self.crop_image) edit_menu.add_command(label="Auto Correct", command=self.auto_correct) edit_menu.add_command(label="Adjust Brightness", command=self.adjust_brightness) edit_menu.add_command(label="Adjust Contrast", command=self.adjust_contrast) edit_menu.add_command(label="Resize", command=self.resize_image) edit_menu.add_command(label="Color Balance", command=self.color_balance) edit_menu.add_command(label="Red Eye Removal", command=self.remove_red_eye) view_menu = tk.Menu(self.menu, tearoff=0) self.menu.add_cascade(label="View", menu=view_menu) view_menu.add_command(label="Draw Histogram", command=self.draw_histogram) view_menu.add_command(label="Image Info", command=self.show_image_info) def open_image(self): file_path = filedialog.askopenfilename(filetypes=[("Image files", "*.jpg *.png *.bmp")]) if file_path: self.processor.load_image(file_path) self.display_image() def save_image(self): if self.processor.image is not None: file_path = filedialog.asksaveasfilename(defaultextension=".jpg", filetypes=[("JPEG", "*.jpg"), ("PNG", "*.png"), ("BMP", "*.bmp")]) if file_path: self.processor.save_image(file_path) def save_image_as(self): if self.processor.image is not None: file_path = filedialog.asksaveasfilename(defaultextension=".jpg", filetypes=[("JPEG", "*.jpg"), ("PNG", "*.png"), ("BMP", "*.bmp")]) if file_path: self.processor.save_image(file_path) def rename_image(self): if self.processor.image is not None: new_name = filedialog.asksaveasfilename(defaultextension=".jpg", filetypes=[("JPEG", "*.jpg"), ("PNG", "*.png"), ("BMP", "*.bmp")]) if new_name: self.processor.save_image(new_name) def clear_image(self): self.processor.image = None self.display_image() def display_image(self): if self.processor.image is not None: img = Image.fromarray(cv2.cvtColor(self.processor.image, cv2.COLOR_BGR2RGB)) img = ImageTk.PhotoImage(img) self.image_label.config(image=img) self.image_label.image = img def zoom_in(self): if self.processor.image is not None: self.processor.resize_image(self.processor.image.shape[1] * 1.2, self.processor.image.shape[0] * 1.2) self.display_image() def zoom_out(self): if self.processor.image is not None: self.processor.resize_image(self.processor.image.shape[1] * 0.8, self.processor.image.shape[0] * 0.8) self.display_image() def rotate_image(self, angle): if self.processor.image is not None: self.processor.rotate_image(angle) self.display_image() def crop_image(self): if self.processor.image is not None: x = int(input("Enter x coordinate: ")) y = int(input("Enter y coordinate: ")) width = int(input("Enter width: ")) height = int(input("Enter height: ")) self.processor.crop_image(x, y, width, height) self.display_image() def auto_correct(self): if self.processor.image is not None: self.processor.auto_correct() self.display_image() def adjust_brightness(self): if self.processor.image is not None: value = int(input("Enter brightness value (-100 to 100): ")) self.processor.adjust_brightness(value) self.display_image() def adjust_contrast(self): if self.processor.image is not None: value = int(input("Enter contrast value (-100 to 100): ")) self.processor.adjust_contrast(value) self.display_image() def resize_image(self): if self.processor.image is not None: width = int(input("Enter new width: ")) height = int(input("Enter new height: ")) self.processor.resize_image(width, height) self.display_image() def color_balance(self): if self.processor.image is not None: red = int(input("Enter red balance (-100 to 100): ")) green = int(input("Enter green balance (-100 to 100): ")) blue = int(input("Enter blue balance (-100 to 100): ")) # Implement color balance logic here pass def remove_red_eye(self): if self.processor.image is not None: # Implement red eye removal logic here pass def draw_histogram(self): if self.processor.image is not None: hist = self.processor.draw_histogram() # Display histogram using matplotlib or another library pass def show_image_info(self): if self.processor.image is not None: info = self.processor.get_image_info() messagebox.showinfo("Image Info", f"Filename: {info['filename']}\nFile Size: {info['file_size']} bytes\nDimensions: {info['dimensions']}\nPosition: {info['position']}") if __name__ == "__main__": root = tk.Tk() app = Application(root) root.mainloop() ``` ### 4. `README.md` - 项目说明 ```markdown # Python Image Processor ## Overview This project is a simple image processing application built using Python and OpenCV. It provides basic functionalities for opening, editing, and saving images. ## Features - File operations: Open, Save, Save As, Rename, Clear - Image editing: Zoom In, Zoom Out, Rotate Left, Rotate Right, Crop, Auto Correct, Adjust Brightness, Adjust Contrast, Resize, Color Balance, Red Eye Removal - Other features: Draw Histogram, Show Image Info ## Requirements - Python 3.x - OpenCV - Tkinter - NumPy - PIL (Pillow) ## Installation 1. Install the required libraries: ```sh pip install opencv-python-headless numpy pillow ``` 2. Run the application: ```sh python main.py ``` ## Usage - Open an image from the "File" menu. - Use the "Edit" menu to apply various image editing operations. - Use the "View" menu to draw histograms and view image information. - Save the edited image using the "File" menu. ## Contributing Feel free to contribute to this project by submitting pull requests or reporting issues. ## License This project is licensed under the MIT License. ``` ### 运行项目 1. 安装所需的库: ```sh pip install opencv-python-headless numpy pillow ``` 2. 运行主程序: ```sh python main.py ``` 这个框架提供了一个基本的图像处理应用程序,涵盖了文档中提到的主要功能。你可以根据需要进一步扩展和完善这些功能。希望这对你有帮助!
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值