python配置OpenCV相对于c++的配置方法容易的多,但建议在Anaconda中的Python虚拟环境中使用,这样更方便进行包管理和环境管理:
先激活Anaconda的python虚拟环境:
conda activate GGBoy
随后下载 opencv 包:
conda install opencv
下载完成后在python终端导入 cv2 测试下是否下载成功
(GGBoy) C:\Users\114514>python
Python 3.6.13 |Anaconda, Inc.| (default, Mar 16 2021, 11:37:27) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>>
使用Opencv显示图像:
import cv2
import sys
if len(sys.argv) > 1:
image = cv2.imread(sys.argv[1], cv2.IMREAD_UNCHANGED)
if image is None:
print(f"未能读取图像文件: {sys.argv[1]}")
sys.exit(1)
else:
print("请提供图像文件路径作为命令行参数。")
sys.exit(1)
cv2.imshow("image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
随后在虚拟环境中运行此文件:
在运行命令后要加上图像的存放路径
(GGBoy) C:\Users\114514>cd C:\Users\114514\Desktop
(GGBoy) C:\Users\114514\Desktop>python cv36.py C:\Users\114514\Desktop\GGBoy.jpg
显示图像
使用Opencv将图片数字化:
import cv2
import numpy as np
image_path = 'C:\\Users\\114514\\Desktop\\GGBoy.jpg'
image = cv2.imread(image_path)
if image is None:
print(f"无法读取图片: {image_path}")
else:
print(f"图片形状: {image.shape}")
print(f"图片数据类型: {image.dtype}")
# 通过numpy数组来访问和操作这些数字化数据
digitized_image = np.array(image)
# 打印数字化矩阵的一部分(左上角的10x10像素)
print(digitized_image[:10, :10])
彩色图片转换为灰度图片:
import cv2
image_path = 'C:\\Users\\114514\\Desktop\\ggboy.jpg'
color_image = cv2.imread(image_path)
if color_image is None:
print(f"未能读取图片: {image_path}")
else:
gray_image = cv2.cvtColor(color_image, cv2.COLOR_BGR2GRAY)
cv2.imshow('GGBoy Image', gray_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
gray_image_path = 'C:\\Users\\114514\\Desktop\\ggboy2.jpg'
cv2.imwrite(gray_image_path, gray_image)