Python OpenCV to Image watermark

Source: Internet
Author: User

Background

Recently there is a need for the picture to go watermark the demand, so various toss start.

"Background understanding of the picture standard"

Images using RGB encoding, RGB color mode is a color standard for industry, is through the red (R), Green (G), Blue (B) three color channels and their superposition to get a variety of colors, RGB is the red, green, blue three channels of color.

"Analyze Picture"

After analyzing the picture, we found the pattern:

1, the picture needs the graphic is black

2, Watermark is a color: shuihong

White corresponds to #ffffff 255 255 255

Black corresponds to #000000 0 0 0

We use the RGB color extraction tool

found that the red Word RGB has the following situation: almost the addition of GRB and all are above 200, then we write the judgment of the program is generated: is to find each pixel, if the pixel and greater than 250, and less than 765 (not white), the pixel reset to white: 255,255,255.

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M00/57/09/wKiom1SPtobjuVmnAACynVQSCD0887.jpg "style=" float: none; "title=" 1.png "alt=" Wkiom1sptobjuvmnaacynvqscd0887.jpg "/>

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M01/57/06/wKioL1SPtyaQF27IAACmD0uzxKA365.jpg "style=" float: none; "title=" 2.png "alt=" Wkiol1sptyaqf27iaacmd0uzxka365.jpg "/>

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M01/57/09/wKiom1SPtofTtOB7AACrw0ual4Q368.jpg "style=" float: none; "title=" 3.png "alt=" Wkiom1sptofttob7aacrw0ual4q368.jpg "/>

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M02/57/06/wKioL1SPtyazDRqAAACscgzUL8Q380.jpg "style=" float: none; "title=" 4.png "alt=" Wkiol1sptyazdrqaaacscgzul8q380.jpg "/>

After getting the above logic, how do you implement it in your code? Found a few python processing images of the library, and finally chose the OpenCV. Then we have to study OpenCV's API.

Specifically, you can see OpenCV's official website: http://opencv.org/

Of course, at first you think it is hard to read the manual, you can also look at other people's programs to find some feeling.

"Install OpenCV"

In fact, install OpenCV is also very frustrating one thing, Mac installation OpenCV installation can refer to:

sudo brew tap homebrew/sciencesudo Brew Install OpenCV


650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M00/57/06/wKioL1SPt0Kz7vQvAAVKUiIbzNI551.jpg "title=" 5.png " alt= "Wkiol1spt0kz7vqvaavkuiibzni551.jpg"/>

Note that after the installation, you need to explain the address of the library, depending on the location of the red box.

There may also be a need

sudo brew update


"specific code

__author__ =  ' River ' # -*- coding: utf-8 -*-import cv2,os,shutil,datetime,re , Timefrom threading import threadfrom hashlib import md5pichash= {}def  md5_file (name):     try:        m = &NBSP;MD5 ()         a_file = open (name,  ' RB ')          m.update (A_file.read ())          a_file.close ()         return m.hexdigest ()      except:        return nonedef nowater (Dir,newdir , dirlist):     global  pichash    for ppicdir in  dirlist:        if (Os.path.isdir (dir+ppicdir)):              sortfiles=os.listdir (Dir+ppicdir)              if  '. Ds_store '  in sortfiles:                 sortfiles.remove ('. Ds_store ')             sortfiles.sort ()              for oldfile in sortfiles:                 filetype= "." +oldfile.split (".") [Len (Oldfile.split (".")) -1]                picname_ Front=oldfile.split (filetype) [0]                 oldfile=dir+ppicdir+ "/" +oldfile                 jpgname=picname_front+ ". jpg"                  jpgname=newdir+ppicdir+ "/" +jpgname                 try:                     oldfile_hash=md5_file (Oldfile)                       Oldfile_tmphashvalue=pichash.get (Oldfile_hash)                      file_object = open (' Pichash.txt ',  ' A ')                      file_object.write (oldfile+ ":" +oldfile_hash+ ' \ n ')               &nBsp;      file_object.close ()                      if (Oldfile_tmphashvalue==none): #新文件, The pictures that have been processed will not be processed again                          if not os.path.exists (Newdir+ppicdir):                              os.makedirs (Newdir+ppicdir)                            #print  oldfile   haha                           #print  jpgname                          print  datetime.datetime.now (). Strftime ("%y-%m-%d %h:%m:%s") + "," +oldfile+ ", ing\n"                           img=cv2.imread (Oldfile)                          x,y,z=img.shape                       &NBSP;&NBSP;&NBSP;IF&NBSP;X&NBSP;&LT;&NBSP;10: #太小文件不处理                               print datetime.datetime.now (). Strftime ("%y-%m-%d %h:%m:%s") + "," +jpgname+ "file too small, skip"                          elif  x >8000: #太大的文件不处理                              print  Datetime.datetime.now (). Strftime ("%y-%m-%d %h:%m:%s") + "," +jpgname+ "file too large, skip"                           elif not os.path.exists (jpgname): #这就是最关键的代码了                               for i in xrange (x):                                  for j&nBsp;in xrange (y):                                      varP=img[i,j]                                      if sum (VarP) >250 and sum (VarP) <765 : #大于250, Less than 765 (sum smaller than white)                                           img[i,j]=[255,255,255]                               #cv2. Imwrite (JpgnamE,img,[int (Cv2. imwrite_jpeg_quality) #linux跑悲剧了                              cv2.imwrite ( JPGNAME,IMG)                              print  "Jpgname:" +jpgname                              PICHASH[oldfile_hash]=oldfile                              print datetime.datetime.now (). Strftime ("%Y-%m-%d %H:%M:%S") + "," + Oldfile+ ", done\n"                          else:                              Print datetime.datetime.now (). Strftime ("%y-%m-%d %h:%m:%s") + "," +jpgname+ "file already exists, skipping \ n"                       Elif (Oldfile_tmphashvalue!=none):                         if (Os.path.exists (jpgname)):                              print datetime.datetime.now (). Strftime ("%Y-%m-%d  %h:%m:%s ") +", "+jpgname+" file already exists, skip \ n "                         else:                              Shutil.copyfile (Oldfile_tmphashvalue,oldfile)                               Shutil.copyfile (Oldfile,jpgname)                              print  Datetime.datetime.now (). Strftime ("%y-%m-%d %h:%m:%s") + "," +jpgname+ "and old files, copy old files, skip"                  except Exception,e:                      print  "Exception:",e                     continueif __name__== ' __main__ ':     dir= "pic/"     newdir= "picnew/ "    list0=[]    list1=[]    list2=[]     list3=[]    list4=[]    for ppicdir in  Os.listdir (dir)  : #生成多个list, mainly for concurrent processing of pictures of multiple catalogs         if ( Os.path.isdir (Dir+ppicdir)):                 if  (Re.compile (R ' ^[0-1].* '). Match (str (ppicdir))):                     list0.append (Ppicdir)                 elif ( Re.compile (R ' ^[2-3].* '). Match (str (ppicdir)): &NBsp;                    list1.append (Ppicdir)                  elif (Re.compile (R ' ^[4-5].* '). Match (str (ppicdir))):                     list2.append (Ppicdir)                 elif ( Re.compile (R ' ^[6-7].* '). Match (str (ppicdir))):                     list3.append (Ppicdir)                  elif (Re.compile (R ' ^[8-9].* '). Match (str (Ppicdir))):                     list4.append (Ppicdir)                 else:                      continue     #启n线程并行处理     thread (target=nowater,args= (Dir,newdir, LIST0). Start () #这里只有     thread (target=nowater,args= (Dir,newdir,list1,)). Start ()      thread (target=nowater,args= (Dir,newdir,list2,)). Start ()     thread (target =nowater,args= (Dir,newdir,list3,)). Start ()     thread (target=nowater,args= (dir,newdir,list4 ,)). Start ()

"Final Effect"

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M02/57/06/wKioL1SPt4CiPm1xAAERfLsyXAQ911.jpg "style=" float: none; "title=" 6.png "alt=" Wkiol1spt4cipm1xaaerflsyxaq911.jpg "/>

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M00/57/09/wKiom1SPtuGSTVNCAACK7N9i7rI815.jpg "style=" float: none; "title=" 7.png "alt=" Wkiom1sptugstvncaack7n9i7ri815.jpg "/>

Effect after watermark removal:

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M02/57/09/wKiom1SPtvOg0clDAABx0GWPcY4695.jpg "title=" 8.png " alt= "Wkiom1sptvog0cldaabx0gwpcy4695.jpg"/>


This article is from "H2O's Operation & Development Road" blog, reprint please contact the author!

Python OpenCV to Image watermark

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.