python去水印

qq_39230217發表於2020-11-01

在做視訊或者圖片處理的時候,我們經常會遇到存在水印的情況,或者我們需要去除圖片的某一個部分,
這時候我們就需要想辦法去除不需要的這一部分。下面這個工具能夠控制滑鼠將圖片上的任意部分改變顏色,
從而達到去除水印的效果,這裡我們預設修改為白色。

一、準備工作

  • 1、CV2庫

  • 2、PIL庫

二、原始碼

import cv2 # 匯入相關庫
from PIL import Image

global img
global point1, point2


def on_mouse(event, x, y, flags, param):
global img, point1, point2
img2 = img.copy()
if event == cv2.EVENT_LBUTTONDOWN: # 左鍵點選
point1 = (x, y)
cv2.circle(img2, point1, 10, (255, 255, 255), 2)
cv2.imshow('image', img2)
elif event == cv2.EVENT_MOUSEMOVE and (flags & cv2.EVENT_FLAG_LBUTTON): # 按住左鍵拖曳
cv2.rectangle(img2, point1, (x, y), (255, 255, 255), 2)
cv2.imshow('image', img2)
elif event == cv2.EVENT_LBUTTONUP: # 左鍵釋放
point2 = (x, y)
cv2.rectangle(img2, point1, point2, (255, 255, 255), 2)
cv2.imshow('image', img2)
min_x = min(point1[0], point2[0])
min_y = min(point1[1], point2[1])
width = abs(point1[0] - point2[0])
height = abs(point1[1] - point2[1])
cut_img = img[min_y:min_y + height, min_x:min_x + width]
cv2.imwrite('first.png',cut_img)

將裁剪出來的圖片變為白色

def test2():
i = 1
j = 1
img = Image.open("first.png") # 讀取系統的內照片
print(img.size) # 列印圖片大小
print(img.getpixel((4, 4)))
width = img.size[0] # 長度
height = img.size[1] # 寬度
for i in range(0, width): # 遍歷所有長度的點
for j in range(0, height): # 遍歷所有寬度的點
data = (img.getpixel((i, j))) # 列印該圖片的所有點
print(data) # 列印每個畫素點的顏色RGBA的值(r,g,b,alpha)
print(data[0]) # 列印RGBA的r值
if (data[0] != 255 and data[1] != 255 and data[2] != 255): # RGBA的r值大於170,並且g值大於170,並且b值大於170
img.putpixel((i, j), (255, 255, 255, 255)) # 則這些畫素點的顏色改成大紅色
img = img.convert("RGB") # 把圖片強制轉成RGB
img.save("mid.png")

def testMain():
img = Image.open('/home/gtwang/1000000.png')
img2 = Image.open('mid.png')

layer = Image.new('RGBA', img.size, (255, 255, 255, 0))
layer.paste(img2, (point1))

img_after = Image.composite(layer, img, layer)
img_after.show()
img_after.save('output.png')

def main():
global img
img = cv2.imread('input.png')
cv2.namedWindow('image')
cv2.setMouseCallback('image', on_mouse)
cv2.imshow('image', img)
cv2.waitKey(0)


if __name__ == '__main__':
main()
test2()
testMain()

相關文章