使用OpenCV 给豆包生成的图片去除水印的命令

2025-07-13 17:33:09 7 分享链接 开发笔记 python

通过图像修复算法(如 inpaint)去除水印。

这行代码的作用是标记出图片中需要去除的水印位置,后续修复算法会根据这个掩码进行处理。调整坐标值 [y1:y2, x1:x2] 即可定位不同位置的水印。
import cv2
import numpy as np

img = cv2.imread('input.jpg')
mask = np.zeros(img.shape[:2], np.uint8)
# 手动指定水印区域(4:3)
mask[40:160, 35:185] = 255
result = cv2.inpaint(img, mask, 3, cv2.INPAINT_TELEA)
cv2.imwrite('output.jpg', result)
OpenCV(Open Source Computer Vision Library)是一个强大的开源计算机视觉库,广泛用于图像处理、计算机视觉、机器学习等领域。以下是OpenCV的核心功能和用法介绍:

一、安装与基础导入

pip install opencv-python
import cv2
import numpy as np  # OpenCV与NumPy紧密结合

二、图像读取、显示与保存

1. 读取图像

img = cv2.imread('image.jpg')  # 返回numpy数组
if img is None:
    print("无法读取图像")

2. 显示图像

cv2.imshow('窗口标题', img)  # 显示图像
cv2.waitKey(0)  # 等待按键
cv2.destroyAllWindows()  # 关闭所有窗口

3. 保存图像

cv2.imwrite('output.jpg', img)  # 保存为JPEG格式

三、图像基本操作

1. 获取图像属性

height, width, channels = img.shape  # 高、宽、通道数
print(f"尺寸: {width}x{height}, 通道数: {channels}")

2. 像素操作

# 获取指定位置的像素值 (BGR顺序)
px = img[100, 100]  # 第100行第100列的像素
print(f"像素值: {px}")  # 输出 [B G R]

# 修改像素值
img[100, 100] = [255, 255, 255]  # 白色

3. 图像裁剪与缩放

# 裁剪 ROI (Region of Interest)
roi = img[100:300, 200:400]  # 高100-300,宽200-400

# 缩放图像
resized = cv2.resize(img, (500, 300))  # 指定宽高
resized = cv2.resize(img, None, fx=0.5, fy=0.5)  # 缩放比例

四、色彩空间转换

1. BGR ↔ Gray

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

2. BGR ↔ HSV

hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

3. 颜色过滤示例

# 提取蓝色物体
lower_blue = np.array([100, 150, 0])
upper_blue = np.array([140, 255, 255])
mask = cv2.inRange(hsv, lower_blue, upper_blue)
result = cv2.bitwise_and(img, img, mask=mask)

五、图像滤波与平滑

1. 高斯模糊

blur = cv2.GaussianBlur(img, (5, 5), 0)  # 5x5内核

2. 中值滤波(去噪)

median = cv2.medianBlur(img, 5)  # 5x5内核

3. 锐化

kernel = np.array([[-1, -1, -1],
                   [-1, 9, -1],
                   [-1, -1, -1]])
sharpened = cv2.filter2D(img, -1, kernel)

六、边缘检测

1. Canny边缘检测

edges = cv2.Canny(img, 100, 200)  # 阈值100和200

2. Sobel算子

sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=3)  # x方向梯度
sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=3)  # y方向梯度

七、形态学操作

1. 膨胀与腐蚀

kernel = np.ones((5, 5), np.uint8)
dilation = cv2.dilate(img, kernel, iterations=1)  # 膨胀
erosion = cv2.erode(img, kernel, iterations=1)    # 腐蚀

2. 开闭运算

opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)  # 先腐蚀后膨胀
closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel) # 先膨胀后腐蚀

八、特征检测

1. 轮廓检测

contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0, 255, 0), 2)  # 绘制所有轮廓

2. 角点检测(Shi-Tomasi)

corners = cv2.goodFeaturesToTrack(gray, 100, 0.01, 10)  # 检测100个角点

3. 霍夫变换(直线检测)

lines = cv2.HoughLinesP(edges, 1, np.pi/180, 100, minLineLength=100, maxLineGap=10)

九、图像修复(去水印)

# 创建掩码(标记水印位置)
mask = np.zeros(gray.shape, np.uint8)
mask[50:150, 200:300] = 255  # 水印区域

# 图像修复
dst = cv2.inpaint(img, mask, 3, cv2.INPAINT_TELEA)

十、视频处理

1. 读取视频

cap = cv2.VideoCapture('video.mp4')  # 读取视频文件
# 或从摄像头捕获
cap = cv2.VideoCapture(0)  # 0表示默认摄像头

while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break
    cv2.imshow('Frame', frame)
    if cv2.waitKey(1) & 0xFF == 27:  # 按ESC退出
        break

cap.release()
cv2.destroyAllWindows()

2. 保存视频

fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480))

# 在循环中写入帧
out.write(frame)

十一、实战案例:物体跟踪

# 使用背景减除实现运动物体检测
fgbg = cv2.createBackgroundSubtractorMOG2()

while True:
    ret, frame = cap.read()
    fgmask = fgbg.apply(frame)  # 背景减除
    contours, _ = cv2.findContours(fgmask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    
    for contour in contours:
        if cv2.contourArea(contour) > 500:  # 过滤小区域
            x, y, w, h = cv2.boundingRect(contour)
            cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
    
    cv2.imshow('Motion Detection', frame)
    if cv2.waitKey(1) == 27:
        break

十二、学习资源

通过以上功能,你可以实现从简单的图像处理到复杂的计算机视觉应用(如人脸识别、自动驾驶等)。建议结合具体项目实践,加深对OpenCV的理解。

使用OpenCV 给豆包生成的图片去除水印的命令