盘点踩过的关于cv2 和PIL 图像读取的一些小坑

本文介绍了cv2与PIL在读取图像时的像素顺序差异,cv2默认为BGR顺序,而PIL为RGB。通过调整cv2的读取方式,可以使其与PIL保持一致。此外,详细解析了cv2.imread()函数的参数flags,包括IMREAD_UNCHANGED、IMREAD_GRAYSCALE、IMREAD_COLOR等,帮助理解图像读取的颜色类型转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、首先像素读取顺序不同

  • PIL 读取图像时的像素顺序是标准的RGB
from PIL import Image
img = Image.open("test.jpg")
print img.size
print img.getpixel((0,0))

输出结果是

(533, 800)
(217, 229, 225)
  • cv2 读取图像时的像素顺序是标准的BGR
img = cv2.imread(""test.jpg"")
print img.shape
print img[0][0]

输出结果是

(800, 533, 3)
[225 229 217]
  • 若要cv2读取完图像也是RGB格式,则按如下方法
img = cv2.imread(""test.jpg"")[..., ::-1]
print img.shape
print img[0][0]

输出结果是

(800, 533, 3)
[217 229 225]

和用PIL 读取完的一致

2、cv2 图像读取方法的参数解释

首先我们先来看一下这个函数的定义
def imread(filename, flags=None)

  • filename
    参数传入的是图像路径,支持解析的图像格式基本上覆盖全了
-   Windows bitmaps - \*.bmp, \*.dib (always supported)
-   JPEG files - \*.jpeg, \*.jpg, \*.jpe (see the *Not
import cv2 import numpy as np from PIL import Image # 参数配置(根据实际情况调整) BLUR_KERNEL_SIZE = (5, 5) # 高斯模糊核大小 MIN_AREA = 50 # 最小坑洞面积阈值 MAX_AREA = 1000 # 最大坑洞面积阈值 FONT_SCALE = 0.7 # 标注字体大小 FONT_COLOR = (255, 0, 0) # 标注颜色 (BGR格式) CONTOUR_COLOR = (0, 255, 0) # 轮廓颜色 (BGR格式) # 读取TIFF图像 image_path = "input.tif" image_pil = Image.open(image_path) image_np = np.array(image_pil) # 转换为灰度图像 if len(image_np.shape) == 3: gray = cv2.cvtColor(image_np, cv2.COLOR_RGB2GRAY) else: gray = image_np.copy() # 图像预处理 blurred = cv2.GaussianBlur(gray, BLUR_KERNEL_SIZE, 0) # 自适应阈值处理 thresh = cv2.adaptiveThreshold( blurred, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 11, 2 ) # 形态学操作(去除小噪点) kernel = np.ones((3, 3), np.uint8) cleaned = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2) # 查找轮廓 contours, _ = cv2.findContours(cleaned, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # 过滤轮廓 filtered_contours = [] for cnt in contours: area = cv2.contourArea(cnt) if MIN_AREA < area < MAX_AREA: filtered_contours.append(cnt) # 创建标注图像 output_image = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR) if len(image_np.shape) == 2 else image_np.copy() # 绘制轮廓标注 for i, cnt in enumerate(filtered_contours): # 计算最小外接圆 (x, y), radius = cv2.minEnclosingCircle(cnt) center = (int(x), int(y)) # center是元组,例如 (100, 200) # 绘制圆形轮廓 cv2.circle(output_image, center, int(radius), CONTOUR_COLOR, 2) # 修正坐标:分别对xy坐标减10(原错误是直接操作元组) text_position = (center[0] - 10, center[1] - 10) # 添加数字标注 cv2.putText(output_image, str(i + 1), text_position, # 使用修正后的坐标 cv2.FONT_HERSHEY_SIMPLEX, FONT_SCALE, FONT_COLOR, 2) # 保存结果 output_image_pil = Image.fromarray(cv2.cvtColor(output_image, cv2.COLOR_BGR2RGB)) output_image_pil.save('output.tif') # 显示结果 print(f"检测到的小坑数量: {len(filtered_contours)}") 这个代码把一些非坑的沟道也算进去了 怎么才能把类似圆形状的小坑才算作小坑
03-14
import cv2 import numpy as np from PIL import Image # 参数配置(根据实际情况调整) BLUR_KERNEL_SIZE = (5, 5) # 高斯模糊核大小 MIN_AREA = 50 # 最小坑洞面积阈值 MAX_AREA = 1000 # 最大坑洞面积阈值 FONT_SCALE = 0.7 # 标注字体大小 FONT_COLOR = (255, 0, 0) # 标注颜色 (BGR格式) CONTOUR_COLOR = (0, 255, 0) # 轮廓颜色 (BGR格式) # 读取TIFF图像 image_path = "input.tif" image_pil = Image.open(image_path) image_np = np.array(image_pil) # 转换为灰度图像 if len(image_np.shape) == 3: gray = cv2.cvtColor(image_np, cv2.COLOR_RGB2GRAY) else: gray = image_np.copy() # 图像预处理 blurred = cv2.GaussianBlur(gray, BLUR_KERNEL_SIZE, 0) # 自适应阈值处理 thresh = cv2.adaptiveThreshold( blurred, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 11, 2 ) # 形态学操作(去除小噪点) kernel = np.ones((3, 3), np.uint8) cleaned = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2) # 查找轮廓 contours, _ = cv2.findContours(cleaned, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # 过滤轮廓 filtered_contours = [] for cnt in contours: area = cv2.contourArea(cnt) if MIN_AREA < area < MAX_AREA: filtered_contours.append(cnt) # 创建标注图像 output_image = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR) if len(image_np.shape) == 2 else image_np.copy() # 绘制轮廓标注 for i, cnt in enumerate(filtered_contours): # 计算最小外接圆 (x, y), radius = cv2.minEnclosingCircle(cnt) center = (int(x), int(y)) # center是元组,例如 (100, 200) # 绘制圆形轮廓 cv2.circle(output_image, center, int(radius), CONTOUR_COLOR, 2) # 修正坐标:分别对xy坐标减10(原错误是直接操作元组) text_position = (center - 10, center - 10) # ✅ 正确拆分元组元素 # 添加数字标注 cv2.putText(output_image, str(i + 1), text_position, # 使用修正后的坐标 cv2.FONT_HERSHEY_SIMPLEX, FONT_SCALE, FONT_COLOR, 2) # 保存结果 output_image_pil = Image.fromarray(cv2.cvtColor(output_image, cv2.COLOR_BGR2RGB)) output_image_pil.save('output.tif') # 显示结果 print(f"检测到的小坑数量: {len(filtered_contours)}")
03-14
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值