在做视频或者图片处理的时候,我们经常会遇到存在水印的情况,或者我们需要去除图片的某一个部分,这时候我们就需要想办法去除不需要的这一部分。下面这个工具能够控制鼠标将图片上的任意部分改变颜色,从而达到去除水印的效果,这里我们默认修改为白色。
一、准备工作
1、CV2库
2、PIL库
二、源码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
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) |
将裁剪出来的图片变为白色
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
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() |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/qq_39230217/article/details/109429342