From e1baccf1ec914563d3b2b845906cce024e7cd3b1 Mon Sep 17 00:00:00 2001 From: Walter Purcaro Date: Tue, 13 Jan 2015 23:14:50 +0100 Subject: Replace 'except' with 'except Exception' --- module/plugins/captcha/LinksaveIn.py | 2 +- module/plugins/captcha/captcha.py | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) (limited to 'module/plugins/captcha') diff --git a/module/plugins/captcha/LinksaveIn.py b/module/plugins/captcha/LinksaveIn.py index 56cbd58a0..de6b0e7ff 100644 --- a/module/plugins/captcha/LinksaveIn.py +++ b/module/plugins/captcha/LinksaveIn.py @@ -79,7 +79,7 @@ class LinksaveIn(OCR): rgb_c = lut[pix[x, y]] try: cstat[rgb_c] += 1 - except: + except Exception: cstat[rgb_c] = 1 if rgb_bg == rgb_c: stat[bgpath] += 1 diff --git a/module/plugins/captcha/captcha.py b/module/plugins/captcha/captcha.py index 0f233ec00..e89ec2e81 100644 --- a/module/plugins/captcha/captcha.py +++ b/module/plugins/captcha/captcha.py @@ -102,7 +102,7 @@ class OCR(object): try: with open(tmpTxt.name, 'r') as f: self.result_captcha = f.read().replace("\n", "") - except: + except Exception: self.result_captcha = "" self.logger.debug(self.result_captcha) @@ -111,7 +111,7 @@ class OCR(object): os.remove(tmpTxt.name) if subset and (digits or lowercase or uppercase): os.remove(tmpSub.name) - except: + except Exception: pass @@ -166,7 +166,7 @@ class OCR(object): count += 1 if pixels[x, y-1] != 255: count += 1 - except: + except Exception: pass # not enough neighbors are dark pixels so mark this pixel -- cgit v1.2.3 From cb9e67a5437ddfafd6a93f5a208b9faf3f2d5575 Mon Sep 17 00:00:00 2001 From: Walter Purcaro Date: Thu, 29 Jan 2015 15:56:57 +0100 Subject: Some file encoding fixup + optimizations --- module/plugins/captcha/captcha.py | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) (limited to 'module/plugins/captcha') diff --git a/module/plugins/captcha/captcha.py b/module/plugins/captcha/captcha.py index e89ec2e81..1874ba07d 100644 --- a/module/plugins/captcha/captcha.py +++ b/module/plugins/captcha/captcha.py @@ -4,6 +4,7 @@ from __future__ import with_statement try: from PIL import Image, GifImagePlugin, JpegImagePlugin, PngImagePlugin, TiffImagePlugin + except ImportError: import Image, GifImagePlugin, JpegImagePlugin, PngImagePlugin, TiffImagePlugin @@ -12,13 +13,13 @@ import os import subprocess #import tempfile -from os.path import abspath, join +from module.utils import save_join class OCR(object): __name__ = "OCR" __type__ = "ocr" - __version__ = "0.10" + __version__ = "0.11" __description__ = """OCR base plugin""" __license__ = "GPLv3" @@ -58,11 +59,11 @@ class OCR(object): def run_tesser(self, subset=False, digits=True, lowercase=True, uppercase=True): #tmpTif = tempfile.NamedTemporaryFile(suffix=".tif") try: - tmpTif = open(join("tmp", "tmpTif_%s.tif" % self.__name__), "wb") + tmpTif = open(save_join("tmp", "tmpTif_%s.tif" % self.__name__), "wb") tmpTif.close() #tmpTxt = tempfile.NamedTemporaryFile(suffix=".txt") - tmpTxt = open(join("tmp", "tmpTxt_%s.txt" % self.__name__), "wb") + tmpTxt = open(save_join("tmp", "tmpTxt_%s.txt" % self.__name__), "wb") tmpTxt.close() except IOError, e: @@ -73,15 +74,15 @@ class OCR(object): self.image.save(tmpTif.name, 'TIFF') if os.name == "nt": - tessparams = [join(pypath, "tesseract", "tesseract.exe")] + tessparams = [os.path.join(pypath, "tesseract", "tesseract.exe")] else: tessparams = ["tesseract"] - tessparams.extend( [abspath(tmpTif.name), abspath(tmpTxt.name).replace(".txt", "")] ) + tessparams.extend( [os.path.abspath(tmpTif.name), os.path.abspath(tmpTxt.name).replace(".txt", "")] ) if subset and (digits or lowercase or uppercase): #tmpSub = tempfile.NamedTemporaryFile(suffix=".subset") - with open(join("tmp", "tmpSub_%s.subset" % self.__name__), "wb") as tmpSub: + with open(save_join("tmp", "tmpSub_%s.subset" % self.__name__), "wb") as tmpSub: tmpSub.write("tessedit_char_whitelist ") if digits: @@ -93,7 +94,7 @@ class OCR(object): tmpSub.write("\n") tessparams.append("nobatch") - tessparams.append(abspath(tmpSub.name)) + tessparams.append(os.path.abspath(tmpSub.name)) self.logger.debug("run tesseract") self.run(tessparams) -- cgit v1.2.3 From de32c12bfc05b3d04df2686373e84494eefed44f Mon Sep 17 00:00:00 2001 From: Walter Purcaro Date: Tue, 24 Feb 2015 22:22:15 +0100 Subject: captcha -> OCR --- module/plugins/captcha/GigasizeCom.py | 4 +- module/plugins/captcha/LinksaveIn.py | 4 +- module/plugins/captcha/NetloadIn.py | 4 +- module/plugins/captcha/OCR.py | 319 +++++++++++++++++++++++++++++++ module/plugins/captcha/ShareonlineBiz.py | 4 +- module/plugins/captcha/captcha.py | 319 ------------------------------- 6 files changed, 327 insertions(+), 327 deletions(-) create mode 100644 module/plugins/captcha/OCR.py delete mode 100644 module/plugins/captcha/captcha.py (limited to 'module/plugins/captcha') diff --git a/module/plugins/captcha/GigasizeCom.py b/module/plugins/captcha/GigasizeCom.py index 244cf6a2a..52c41729b 100644 --- a/module/plugins/captcha/GigasizeCom.py +++ b/module/plugins/captcha/GigasizeCom.py @@ -1,12 +1,12 @@ # -*- coding: utf-8 -*- -from module.plugins.captcha.captcha import OCR +from module.plugins.captcha.OCR import OCR class GigasizeCom(OCR): __name__ = "GigasizeCom" __type__ = "ocr" - __version__ = "0.10" + __version__ = "0.11" __description__ = """Gigasize.com ocr plugin""" __license__ = "GPLv3" diff --git a/module/plugins/captcha/LinksaveIn.py b/module/plugins/captcha/LinksaveIn.py index de6b0e7ff..b5cb0f608 100644 --- a/module/plugins/captcha/LinksaveIn.py +++ b/module/plugins/captcha/LinksaveIn.py @@ -9,13 +9,13 @@ from glob import glob from os import sep from os.path import abspath, dirname -from module.plugins.captcha.captcha import OCR +from module.plugins.captcha.OCR import OCR class LinksaveIn(OCR): __name__ = "LinksaveIn" __type__ = "ocr" - __version__ = "0.10" + __version__ = "0.11" __description__ = """Linksave.in ocr plugin""" __license__ = "GPLv3" diff --git a/module/plugins/captcha/NetloadIn.py b/module/plugins/captcha/NetloadIn.py index 28eb18fb5..1fb258c47 100644 --- a/module/plugins/captcha/NetloadIn.py +++ b/module/plugins/captcha/NetloadIn.py @@ -1,12 +1,12 @@ # -*- coding: utf-8 -*- -from module.plugins.captcha.captcha import OCR +from module.plugins.captcha.OCR import OCR class NetloadIn(OCR): __name__ = "NetloadIn" __type__ = "ocr" - __version__ = "0.10" + __version__ = "0.11" __description__ = """Netload.in ocr plugin""" __license__ = "GPLv3" diff --git a/module/plugins/captcha/OCR.py b/module/plugins/captcha/OCR.py new file mode 100644 index 000000000..1874ba07d --- /dev/null +++ b/module/plugins/captcha/OCR.py @@ -0,0 +1,319 @@ +# -*- coding: utf-8 -*- + +from __future__ import with_statement + +try: + from PIL import Image, GifImagePlugin, JpegImagePlugin, PngImagePlugin, TiffImagePlugin + +except ImportError: + import Image, GifImagePlugin, JpegImagePlugin, PngImagePlugin, TiffImagePlugin + +import logging +import os +import subprocess +#import tempfile + +from module.utils import save_join + + +class OCR(object): + __name__ = "OCR" + __type__ = "ocr" + __version__ = "0.11" + + __description__ = """OCR base plugin""" + __license__ = "GPLv3" + __authors__ = [("pyLoad Team", "admin@pyload.org")] + + + def __init__(self): + self.logger = logging.getLogger("log") + + + def load_image(self, image): + self.image = Image.open(image) + self.pixels = self.image.load() + self.result_captcha = '' + + + def unload(self): + """delete all tmp images""" + pass + + + def threshold(self, value): + self.image = self.image.point(lambda a: a * value + 10) + + + def run(self, command): + """Run a command""" + + popen = subprocess.Popen(command, bufsize = -1, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + popen.wait() + output = popen.stdout.read() +" | "+ popen.stderr.read() + popen.stdout.close() + popen.stderr.close() + self.logger.debug("Tesseract ReturnCode %s Output: %s" % (popen.returncode, output)) + + + def run_tesser(self, subset=False, digits=True, lowercase=True, uppercase=True): + #tmpTif = tempfile.NamedTemporaryFile(suffix=".tif") + try: + tmpTif = open(save_join("tmp", "tmpTif_%s.tif" % self.__name__), "wb") + tmpTif.close() + + #tmpTxt = tempfile.NamedTemporaryFile(suffix=".txt") + tmpTxt = open(save_join("tmp", "tmpTxt_%s.txt" % self.__name__), "wb") + tmpTxt.close() + + except IOError, e: + self.logError(e) + return + + self.logger.debug("save tiff") + self.image.save(tmpTif.name, 'TIFF') + + if os.name == "nt": + tessparams = [os.path.join(pypath, "tesseract", "tesseract.exe")] + else: + tessparams = ["tesseract"] + + tessparams.extend( [os.path.abspath(tmpTif.name), os.path.abspath(tmpTxt.name).replace(".txt", "")] ) + + if subset and (digits or lowercase or uppercase): + #tmpSub = tempfile.NamedTemporaryFile(suffix=".subset") + with open(save_join("tmp", "tmpSub_%s.subset" % self.__name__), "wb") as tmpSub: + tmpSub.write("tessedit_char_whitelist ") + + if digits: + tmpSub.write("0123456789") + if lowercase: + tmpSub.write("abcdefghijklmnopqrstuvwxyz") + if uppercase: + tmpSub.write("ABCDEFGHIJKLMNOPQRSTUVWXYZ") + + tmpSub.write("\n") + tessparams.append("nobatch") + tessparams.append(os.path.abspath(tmpSub.name)) + + self.logger.debug("run tesseract") + self.run(tessparams) + self.logger.debug("read txt") + + try: + with open(tmpTxt.name, 'r') as f: + self.result_captcha = f.read().replace("\n", "") + except Exception: + self.result_captcha = "" + + self.logger.debug(self.result_captcha) + try: + os.remove(tmpTif.name) + os.remove(tmpTxt.name) + if subset and (digits or lowercase or uppercase): + os.remove(tmpSub.name) + except Exception: + pass + + + def get_captcha(self, name): + raise NotImplementedError + + + def to_greyscale(self): + if self.image.mode != 'L': + self.image = self.image.convert('L') + + self.pixels = self.image.load() + + + def eval_black_white(self, limit): + self.pixels = self.image.load() + w, h = self.image.size + for x in xrange(w): + for y in xrange(h): + if self.pixels[x, y] > limit: + self.pixels[x, y] = 255 + else: + self.pixels[x, y] = 0 + + + def clean(self, allowed): + pixels = self.pixels + + w, h = self.image.size + + for x in xrange(w): + for y in xrange(h): + if pixels[x, y] == 255: + continue + # No point in processing white pixels since we only want to remove black pixel + count = 0 + + try: + if pixels[x-1, y-1] != 255: + count += 1 + if pixels[x-1, y] != 255: + count += 1 + if pixels[x-1, y + 1] != 255: + count += 1 + if pixels[x, y + 1] != 255: + count += 1 + if pixels[x + 1, y + 1] != 255: + count += 1 + if pixels[x + 1, y] != 255: + count += 1 + if pixels[x + 1, y-1] != 255: + count += 1 + if pixels[x, y-1] != 255: + count += 1 + except Exception: + pass + + # not enough neighbors are dark pixels so mark this pixel + # to be changed to white + if count < allowed: + pixels[x, y] = 1 + + # second pass: this time set all 1's to 255 (white) + for x in xrange(w): + for y in xrange(h): + if pixels[x, y] == 1: + pixels[x, y] = 255 + + self.pixels = pixels + + + def derotate_by_average(self): + """rotate by checking each angle and guess most suitable""" + + w, h = self.image.size + pixels = self.pixels + + for x in xrange(w): + for y in xrange(h): + if pixels[x, y] == 0: + pixels[x, y] = 155 + + highest = {} + counts = {} + + for angle in xrange(-45, 45): + + tmpimage = self.image.rotate(angle) + + pixels = tmpimage.load() + + w, h = self.image.size + + for x in xrange(w): + for y in xrange(h): + if pixels[x, y] == 0: + pixels[x, y] = 255 + + + count = {} + + for x in xrange(w): + count[x] = 0 + for y in xrange(h): + if pixels[x, y] == 155: + count[x] += 1 + + sum = 0 + cnt = 0 + + for x in count.values(): + if x != 0: + sum += x + cnt += 1 + + avg = sum / cnt + counts[angle] = cnt + highest[angle] = 0 + for x in count.values(): + if x > highest[angle]: + highest[angle] = x + + highest[angle] = highest[angle] - avg + + hkey = 0 + hvalue = 0 + + for key, value in highest.iteritems(): + if value > hvalue: + hkey = key + hvalue = value + + self.image = self.image.rotate(hkey) + pixels = self.image.load() + + for x in xrange(w): + for y in xrange(h): + if pixels[x, y] == 0: + pixels[x, y] = 255 + + if pixels[x, y] == 155: + pixels[x, y] = 0 + + self.pixels = pixels + + + def split_captcha_letters(self): + captcha = self.image + started = False + letters = [] + width, height = captcha.size + bottomY, topY = 0, height + pixels = captcha.load() + + for x in xrange(width): + black_pixel_in_col = False + for y in xrange(height): + if pixels[x, y] != 255: + if not started: + started = True + firstX = x + lastX = x + + if y > bottomY: + bottomY = y + if y < topY: + topY = y + if x > lastX: + lastX = x + + black_pixel_in_col = True + + if black_pixel_in_col is False and started is True: + rect = (firstX, topY, lastX, bottomY) + new_captcha = captcha.crop(rect) + + w, h = new_captcha.size + if w > 5 and h > 5: + letters.append(new_captcha) + + started = False + bottomY, topY = 0, height + + return letters + + + def correct(self, values, var=None): + if var: + result = var + else: + result = self.result_captcha + + for key, item in values.iteritems(): + + if key.__class__ == str: + result = result.replace(key, item) + else: + for expr in key: + result = result.replace(expr, item) + + if var: + return result + else: + self.result_captcha = result diff --git a/module/plugins/captcha/ShareonlineBiz.py b/module/plugins/captcha/ShareonlineBiz.py index 8210e8859..6fad66600 100644 --- a/module/plugins/captcha/ShareonlineBiz.py +++ b/module/plugins/captcha/ShareonlineBiz.py @@ -1,12 +1,12 @@ # -*- coding: utf-8 -*- -from module.plugins.captcha.captcha import OCR +from module.plugins.captcha.OCR import OCR class ShareonlineBiz(OCR): __name__ = "ShareonlineBiz" __type__ = "ocr" - __version__ = "0.10" + __version__ = "0.11" __description__ = """Shareonline.biz ocr plugin""" __license__ = "GPLv3" diff --git a/module/plugins/captcha/captcha.py b/module/plugins/captcha/captcha.py deleted file mode 100644 index 1874ba07d..000000000 --- a/module/plugins/captcha/captcha.py +++ /dev/null @@ -1,319 +0,0 @@ -# -*- coding: utf-8 -*- - -from __future__ import with_statement - -try: - from PIL import Image, GifImagePlugin, JpegImagePlugin, PngImagePlugin, TiffImagePlugin - -except ImportError: - import Image, GifImagePlugin, JpegImagePlugin, PngImagePlugin, TiffImagePlugin - -import logging -import os -import subprocess -#import tempfile - -from module.utils import save_join - - -class OCR(object): - __name__ = "OCR" - __type__ = "ocr" - __version__ = "0.11" - - __description__ = """OCR base plugin""" - __license__ = "GPLv3" - __authors__ = [("pyLoad Team", "admin@pyload.org")] - - - def __init__(self): - self.logger = logging.getLogger("log") - - - def load_image(self, image): - self.image = Image.open(image) - self.pixels = self.image.load() - self.result_captcha = '' - - - def unload(self): - """delete all tmp images""" - pass - - - def threshold(self, value): - self.image = self.image.point(lambda a: a * value + 10) - - - def run(self, command): - """Run a command""" - - popen = subprocess.Popen(command, bufsize = -1, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - popen.wait() - output = popen.stdout.read() +" | "+ popen.stderr.read() - popen.stdout.close() - popen.stderr.close() - self.logger.debug("Tesseract ReturnCode %s Output: %s" % (popen.returncode, output)) - - - def run_tesser(self, subset=False, digits=True, lowercase=True, uppercase=True): - #tmpTif = tempfile.NamedTemporaryFile(suffix=".tif") - try: - tmpTif = open(save_join("tmp", "tmpTif_%s.tif" % self.__name__), "wb") - tmpTif.close() - - #tmpTxt = tempfile.NamedTemporaryFile(suffix=".txt") - tmpTxt = open(save_join("tmp", "tmpTxt_%s.txt" % self.__name__), "wb") - tmpTxt.close() - - except IOError, e: - self.logError(e) - return - - self.logger.debug("save tiff") - self.image.save(tmpTif.name, 'TIFF') - - if os.name == "nt": - tessparams = [os.path.join(pypath, "tesseract", "tesseract.exe")] - else: - tessparams = ["tesseract"] - - tessparams.extend( [os.path.abspath(tmpTif.name), os.path.abspath(tmpTxt.name).replace(".txt", "")] ) - - if subset and (digits or lowercase or uppercase): - #tmpSub = tempfile.NamedTemporaryFile(suffix=".subset") - with open(save_join("tmp", "tmpSub_%s.subset" % self.__name__), "wb") as tmpSub: - tmpSub.write("tessedit_char_whitelist ") - - if digits: - tmpSub.write("0123456789") - if lowercase: - tmpSub.write("abcdefghijklmnopqrstuvwxyz") - if uppercase: - tmpSub.write("ABCDEFGHIJKLMNOPQRSTUVWXYZ") - - tmpSub.write("\n") - tessparams.append("nobatch") - tessparams.append(os.path.abspath(tmpSub.name)) - - self.logger.debug("run tesseract") - self.run(tessparams) - self.logger.debug("read txt") - - try: - with open(tmpTxt.name, 'r') as f: - self.result_captcha = f.read().replace("\n", "") - except Exception: - self.result_captcha = "" - - self.logger.debug(self.result_captcha) - try: - os.remove(tmpTif.name) - os.remove(tmpTxt.name) - if subset and (digits or lowercase or uppercase): - os.remove(tmpSub.name) - except Exception: - pass - - - def get_captcha(self, name): - raise NotImplementedError - - - def to_greyscale(self): - if self.image.mode != 'L': - self.image = self.image.convert('L') - - self.pixels = self.image.load() - - - def eval_black_white(self, limit): - self.pixels = self.image.load() - w, h = self.image.size - for x in xrange(w): - for y in xrange(h): - if self.pixels[x, y] > limit: - self.pixels[x, y] = 255 - else: - self.pixels[x, y] = 0 - - - def clean(self, allowed): - pixels = self.pixels - - w, h = self.image.size - - for x in xrange(w): - for y in xrange(h): - if pixels[x, y] == 255: - continue - # No point in processing white pixels since we only want to remove black pixel - count = 0 - - try: - if pixels[x-1, y-1] != 255: - count += 1 - if pixels[x-1, y] != 255: - count += 1 - if pixels[x-1, y + 1] != 255: - count += 1 - if pixels[x, y + 1] != 255: - count += 1 - if pixels[x + 1, y + 1] != 255: - count += 1 - if pixels[x + 1, y] != 255: - count += 1 - if pixels[x + 1, y-1] != 255: - count += 1 - if pixels[x, y-1] != 255: - count += 1 - except Exception: - pass - - # not enough neighbors are dark pixels so mark this pixel - # to be changed to white - if count < allowed: - pixels[x, y] = 1 - - # second pass: this time set all 1's to 255 (white) - for x in xrange(w): - for y in xrange(h): - if pixels[x, y] == 1: - pixels[x, y] = 255 - - self.pixels = pixels - - - def derotate_by_average(self): - """rotate by checking each angle and guess most suitable""" - - w, h = self.image.size - pixels = self.pixels - - for x in xrange(w): - for y in xrange(h): - if pixels[x, y] == 0: - pixels[x, y] = 155 - - highest = {} - counts = {} - - for angle in xrange(-45, 45): - - tmpimage = self.image.rotate(angle) - - pixels = tmpimage.load() - - w, h = self.image.size - - for x in xrange(w): - for y in xrange(h): - if pixels[x, y] == 0: - pixels[x, y] = 255 - - - count = {} - - for x in xrange(w): - count[x] = 0 - for y in xrange(h): - if pixels[x, y] == 155: - count[x] += 1 - - sum = 0 - cnt = 0 - - for x in count.values(): - if x != 0: - sum += x - cnt += 1 - - avg = sum / cnt - counts[angle] = cnt - highest[angle] = 0 - for x in count.values(): - if x > highest[angle]: - highest[angle] = x - - highest[angle] = highest[angle] - avg - - hkey = 0 - hvalue = 0 - - for key, value in highest.iteritems(): - if value > hvalue: - hkey = key - hvalue = value - - self.image = self.image.rotate(hkey) - pixels = self.image.load() - - for x in xrange(w): - for y in xrange(h): - if pixels[x, y] == 0: - pixels[x, y] = 255 - - if pixels[x, y] == 155: - pixels[x, y] = 0 - - self.pixels = pixels - - - def split_captcha_letters(self): - captcha = self.image - started = False - letters = [] - width, height = captcha.size - bottomY, topY = 0, height - pixels = captcha.load() - - for x in xrange(width): - black_pixel_in_col = False - for y in xrange(height): - if pixels[x, y] != 255: - if not started: - started = True - firstX = x - lastX = x - - if y > bottomY: - bottomY = y - if y < topY: - topY = y - if x > lastX: - lastX = x - - black_pixel_in_col = True - - if black_pixel_in_col is False and started is True: - rect = (firstX, topY, lastX, bottomY) - new_captcha = captcha.crop(rect) - - w, h = new_captcha.size - if w > 5 and h > 5: - letters.append(new_captcha) - - started = False - bottomY, topY = 0, height - - return letters - - - def correct(self, values, var=None): - if var: - result = var - else: - result = self.result_captcha - - for key, item in values.iteritems(): - - if key.__class__ == str: - result = result.replace(key, item) - else: - for expr in key: - result = result.replace(expr, item) - - if var: - return result - else: - self.result_captcha = result -- cgit v1.2.3 From 7beb65e991bc6d1913c3b5bb2ef69e659d5b8342 Mon Sep 17 00:00:00 2001 From: Walter Purcaro Date: Tue, 10 Mar 2015 01:55:52 +0100 Subject: Spare code cosmetics --- module/plugins/captcha/LinksaveIn.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'module/plugins/captcha') diff --git a/module/plugins/captcha/LinksaveIn.py b/module/plugins/captcha/LinksaveIn.py index b5cb0f608..a7ae715fe 100644 --- a/module/plugins/captcha/LinksaveIn.py +++ b/module/plugins/captcha/LinksaveIn.py @@ -46,7 +46,7 @@ class LinksaveIn(OCR): pix = frame.load() for x in xrange(frame.size[0]): for y in xrange(frame.size[1]): - if lut[pix[x, y]] != (0,0,0): + if lut[pix[x, y]] != (0, 0, 0): npix[x, y] = lut[pix[x, y]] frame_nr += 1 new.save(self.data_dir+"unblacked.png") @@ -112,7 +112,7 @@ class LinksaveIn(OCR): rgb_bg = bglut[bgpix[x, y]] rgb_c = lut[pix[x, y]] if rgb_c == rgb_bg: - orgpix[x, y] = (255,255,255) + orgpix[x, y] = (255, 255, 255) def eval_black_white(self): @@ -126,13 +126,13 @@ class LinksaveIn(OCR): r, g, b = rgb pix[x, y] = (255,255,255) if r > max(b, g)+thresh: - pix[x, y] = (0,0,0) + pix[x, y] = (0, 0, 0) if g < min(r, b): - pix[x, y] = (0,0,0) + pix[x, y] = (0, 0, 0) if g > max(r, b)+thresh: - pix[x, y] = (0,0,0) + pix[x, y] = (0, 0, 0) if b > max(r, g)+thresh: - pix[x, y] = (0,0,0) + pix[x, y] = (0, 0, 0) self.image = new self.pixels = self.image.load() -- cgit v1.2.3 From 589121e80835c63aea0880a53c6678de5c31c16e Mon Sep 17 00:00:00 2001 From: Walter Purcaro Date: Sat, 28 Mar 2015 01:59:01 +0100 Subject: Spare code cosmetics --- module/plugins/captcha/LinksaveIn.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'module/plugins/captcha') diff --git a/module/plugins/captcha/LinksaveIn.py b/module/plugins/captcha/LinksaveIn.py index a7ae715fe..e256da502 100644 --- a/module/plugins/captcha/LinksaveIn.py +++ b/module/plugins/captcha/LinksaveIn.py @@ -124,7 +124,7 @@ class LinksaveIn(OCR): for y in xrange(new.size[1]): rgb = orgpix[x, y] r, g, b = rgb - pix[x, y] = (255,255,255) + pix[x, y] = (255, 255, 255) if r > max(b, g)+thresh: pix[x, y] = (0, 0, 0) if g < min(r, b): -- cgit v1.2.3 From 1ef93e913238275f7657d496ba3d2e7eeb5a30a2 Mon Sep 17 00:00:00 2001 From: Walter Purcaro Date: Fri, 1 May 2015 01:06:01 +0200 Subject: Use 'import' instead 'from' --- module/plugins/captcha/LinksaveIn.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) (limited to 'module/plugins/captcha') diff --git a/module/plugins/captcha/LinksaveIn.py b/module/plugins/captcha/LinksaveIn.py index e256da502..95b107977 100644 --- a/module/plugins/captcha/LinksaveIn.py +++ b/module/plugins/captcha/LinksaveIn.py @@ -5,9 +5,8 @@ try: except ImportError: import Image -from glob import glob -from os import sep -from os.path import abspath, dirname +import glob +import os from module.plugins.captcha.OCR import OCR @@ -24,7 +23,7 @@ class LinksaveIn(OCR): def __init__(self): OCR.__init__(self) - self.data_dir = dirname(abspath(__file__)) + sep + "LinksaveIn" + sep + self.data_dir = os.path.dirname(os.path.abspath(__file__)) + os.sep + "LinksaveIn" + os.sep def load_image(self, image): @@ -59,7 +58,7 @@ class LinksaveIn(OCR): stat = {} cstat = {} img = self.image.convert("P") - for bgpath in glob(self.data_dir+"bg/*.gif"): + for bgpath in glob.glob(self.data_dir+"bg/*.gif"): stat[bgpath] = 0 bg = Image.open(bgpath) -- cgit v1.2.3 From d22cf4a5b0e51716c353e9f2504eb02ae879501d Mon Sep 17 00:00:00 2001 From: gsasch Date: Mon, 18 May 2015 16:23:37 +0200 Subject: New OCR CircleCaptcha --- module/plugins/captcha/CircleCaptcha.py | 781 ++++++++++++++++++++++++++++++++ 1 file changed, 781 insertions(+) create mode 100644 module/plugins/captcha/CircleCaptcha.py (limited to 'module/plugins/captcha') diff --git a/module/plugins/captcha/CircleCaptcha.py b/module/plugins/captcha/CircleCaptcha.py new file mode 100644 index 000000000..d4f08018d --- /dev/null +++ b/module/plugins/captcha/CircleCaptcha.py @@ -0,0 +1,781 @@ +# -*- coding: utf-8 -*- + +from __future__ import division + +import Image +import ImageDraw +import cStringIO +import math +import operator +import urllib + +from module.plugins.captcha.OCR import OCR + + +class ImageSequence: + + def __init__(self, im): + self.im = im + + def __getitem__(self, ix): + try: + if ix: + self.im.seek(ix) + return self.im + except EOFError: + raise IndexError # end of sequence + + +class CircleCaptcha(OCR): + __name__ = "CircleCaptcha" + __type__ = "ocr" + __version__ = "1.00" + + __description__ = """Circle captcha ocr plugin""" + __license__ = "GPLv3" + __authors__ = [("Sasch", "gsasch@gmail.com")] + + + _DEBUG = False + pointsofcirclefound = [] + + BACKGROUND = 250 + BLACKCOLOR = 5 + + + def cleanImage(self, im, pix): + cleandeep = 1 + + imageheight = range(1,int(im.size[1])) + imagewidth = range(1,int(im.size[0])) + howmany = 0 + curcolor = self.BACKGROUND + + for y in imageheight: + jump = True + howmany = 0 + for x in imagewidth: + curpix = pix[x,y] + + if curpix > self.BACKGROUND: + if howmany <= cleandeep and howmany > 0: + # clean pixel + for ic in range(1,cleandeep+1): + if x -ic > 0: + pix[x-ic,y] = self.BACKGROUND + jump = False + howmany = 0 + curcolor = curpix + # print (x, y), jump,2 + else: + if howmany == 0: + # found pixel + jump = True + howmany = howmany + 1 + curcolor = curpix + # print (x, y), jump,2 + else: + howmany = howmany + 1 + if howmany == 1: + # clean pixel + pix[x-1,y] = self.BACKGROUND + + curcolor = self.BACKGROUND + for x in imagewidth: + jump = True + howmany = 0 + for y in imageheight: + curpix = pix[x,y] + # if jump == True: + if curpix > self.BACKGROUND: + if howmany <= cleandeep and howmany > 0: + # clean pixel + for ic in range(1,cleandeep+1): + # raw_input('2'+str(ic)) + if y-ic > 0: + pix[x,y-ic] = self.BACKGROUND + jump = False + howmany = 0 + curcolor = curpix + # print (x, y), jump + else: + if howmany == 0: + # found pixel + jump = True + howmany = howmany + 1 + curcolor = curpix + # print (x, y), jump + else: + howmany = howmany + 1 + if howmany == 1: + # clean pixel + pix[x-1,y] = self.BACKGROUND + + # return -1 + + + def findFirstPixelX(self, im, pix, curx, cury, color = -1, ExitWithBlack = False): + imageheight = range(1,int(im.size[1])) + imagewidth = range(curx+1,int(im.size[0])) + jump = True + newx = (-1,-1) + blackfound = 0 + for x in imagewidth: + curpix = pix[x,cury] + + if curpix < self.BLACKCOLOR: + blackfound = blackfound + 1 + if ExitWithBlack == True and blackfound >= 3: + break; #exit if found black + else: + continue; + + if curpix >= self.BACKGROUND: + # found first pixel white + jump = False + continue; + + if (curpix < self.BACKGROUND and color == -1) or (curpix == color and color > -1): + if jump == False: + # found pixel + curcolor = curpix + newx = x, curcolor + break; + + return newx + + + def findLastPixelX(self, im, pix, curx, cury, color = -1, ExitWithBlack = False): + imageheight = range(1,int(im.size[1])) + imagewidth = range(curx+1,int(im.size[0])) + newx = (-1,-1) + blackfound = 0 + for x in imagewidth: + curpix = pix[x,cury] + + if curpix < self.BLACKCOLOR: + blackfound = blackfound + 1 + if ExitWithBlack == True and blackfound >= 3: + break; #exit if found black + else: + continue; + + if curpix >= self.BACKGROUND: + if newx != (-1,-1): + # found last pixel and the first white + break; + + if (curpix < self.BACKGROUND and color == -1) or (curpix == color and color > -1): + # found pixel + curcolor = curpix + newx = x, curcolor + + return newx + + + def findLastPixelY(self, im, pix, curx, cury, DownToUp, color = -1, ExitWithBlack = False): + if DownToUp == False: + imageheight = range(int(cury)+1,int(im.size[1])-1) + else: + imageheight = range(int(cury)-1,1,-1) + imagewidth = range(int(curx),int(im.size[0])) + newy = (-1,-1) + blackfound = 0 + for y in imageheight: + curpix = pix[curx,y] + + if curpix < self.BLACKCOLOR: + blackfound = blackfound + 1 + if ExitWithBlack == True and blackfound >= 3: + break; #exit if found black + else: + continue; + + if curpix >= self.BACKGROUND: + if newy != (-1,-1): + # found last pixel and the first white + break; + + if (curpix < self.BACKGROUND and color == -1) or (curpix == color and color > -1): + # found pixel + curcolor = curpix + newy = y, color + + return newy + + + def findCircle(self, pix, x1, y1, x2, y2, x3, y3): + # trasposizione coordinate + # A(0,0) B(x2-x1,y2-y1) C(x3-x1,y3-y1) + # x**2+y**2+ax+bx+c=0 + p1 = (0,0) + p2 = (x2-x1,y2-y1) + p3 = (x3-x1,y3-y1) + + # 1 + c=0 + # 2 + # p2[0]**2+a*p2[0]+c=0 + # a*p2[0]=-1*(p2[0]**2-c) + # a=(-1*(p2[0]**2-c))/p2[0] + a=(-1*(p2[0]**2-c))/p2[0] + # 3 + # p3[0]**2+p3[1]**2+a*p3[0]+b*p3[1]+c=0 + # b*p3[1]=-(p3[0]**2+p3[1]**2+a*p3[0]+c) + # b=(-1 * (p3[0]**2+p3[1]**2+a*p3[0]+c)) / p3[1] + b=(-1 * (p3[0]**2+p3[1]**2+a*p3[0]+c)) / p3[1] + + r=math.floor(math.sqrt((-1*(a/2))**2+(-1*(b/2))**2)) + cx=math.floor((-1*(a/2))+x1) + cy=math.floor((-1*(b/2))+y1) + + return cx,cy,r + + + def verifyCircleNew(self, im, pix, c): + """ + This is the MAIN function to recognize the circle + returns: + 1 -> Found closed circle + 0 -> Found open circle + -1 -> Not found circle + -2 -> Found black position then leave position + """ + + imageheight = range(int(c[1]-c[2]),int(c[1]+c[2])) + imagewidth = range(int(c[0]-c[2]),int(c[0]+c[2])) + + min_ray = 15 + max_ray = 30 + exactfind = False + + howmany = 0 + missing = 0 + missingconsecutive = 0 + missinglist = [] + minX = 0; maxX = 0; minY = 0; maxY = 0 + pointsofcircle = [] + + if (c[2] < min_ray) or (c[2] > max_ray): + return -1 + + # check cardinal points (at least 3) (if found i have to leave this position) + if pix[c[0] + c[2],c[1]] < self.BLACKCOLOR: + return -2; + if pix[c[0] - c[2],c[1]] < self.BLACKCOLOR: + return -2; + if pix[c[0],c[1] + c[2]] < self.BLACKCOLOR: + return -2; + if pix[c[0],c[1] - c[2]] < self.BLACKCOLOR: + return -2; + + cardinalpoints = 0 + if self.verifyPoint(im, pix,c[0] + c[2],c[1],True) == 1: + cardinalpoints = cardinalpoints + 1 + if self.verifyPoint(im, pix,c[0] + c[2],c[1],False) == -1: + return -2; + if self.verifyPoint(im, pix,c[0] - c[2],c[1],True) == 1: + cardinalpoints = cardinalpoints + 1 + if self.verifyPoint(im, pix,c[0] - c[2],c[1],False) == -1: + return -2; + if self.verifyPoint(im, pix,c[0],c[1] + c[2],True) == 1: + cardinalpoints = cardinalpoints + 1 + if self.verifyPoint(im, pix,c[0],c[1] + c[2],False) == -1: + return -2; + if self.verifyPoint(im, pix,c[0],c[1] - c[2],True) == 1: + cardinalpoints = cardinalpoints + 1 + if self.verifyPoint(im, pix,c[0],c[1] - c[2],False) == -1: + return -2; + if cardinalpoints < 3: + return -1; + + for x in imagewidth: + # Pitagora + y = int(round(c[1]- math.sqrt(c[2]**2-(c[0]-x)**2))) + y2= int(round(c[1]+ math.sqrt(c[2]**2-(c[0]-x)**2))) + + howmany = howmany + 2 + if self.verifyPoint(im, pix, x,y,exactfind) == 0: + missing = missing + 1 + missinglist.append((x,y)) + else: + pointsofcircle.append((x,y)) + + if self.verifyPoint(im, pix, x,y,False) == -1: + return -2; + + if self.verifyPoint(im, pix, x,y2,exactfind) == 0: + missing = missing + 1 + missinglist.append((x,y2)) + else: + pointsofcircle.append((x,y2)) + + if self.verifyPoint(im, pix, x,y2,False) == -1: + return -2; + + + def verifyCircle(self, im, pix, c): + """ + This is the MAIN function to recognize the circle + returns: + 1 -> Found closed circle + 0 -> Found open circle + -1 -> Not found circle + -2 -> Found black position then leave position + """ + + imageheight = range(int(c[1]-c[2]),int(c[1]+c[2])) + imagewidth = range(int(c[0]-c[2]),int(c[0]+c[2])) + + min_ray = 15 + max_ray = 30 + exactfind = False + + howmany = 0 + missing = 0 + missingconsecutive = 0 + missinglist = [] + minX = 0; maxX = 0; minY = 0; maxY = 0 + pointsofcircle = [] + + if (c[2] < min_ray) or (c[2] > max_ray): + return -1 + + # check cardinal points (at least 3) (if found i have to leave this position) + if pix[c[0] + c[2],c[1]] < self.BLACKCOLOR: + return -2; + if pix[c[0] - c[2],c[1]] < self.BLACKCOLOR: + return -2; + if pix[c[0],c[1] + c[2]] < self.BLACKCOLOR: + return -2; + if pix[c[0],c[1] - c[2]] < self.BLACKCOLOR: + return -2; + + cardinalpoints = 0 + if self.verifyPoint(im, pix,c[0] + c[2],c[1],True) == 1: + cardinalpoints = cardinalpoints + 1 + if self.verifyPoint(im, pix,c[0] + c[2],c[1],False) == -1: + return -2; + if self.verifyPoint(im, pix,c[0] - c[2],c[1],True) == 1: + cardinalpoints = cardinalpoints + 1 + if self.verifyPoint(im, pix,c[0] - c[2],c[1],False) == -1: + return -2; + if self.verifyPoint(im, pix,c[0],c[1] + c[2],True) == 1: + cardinalpoints = cardinalpoints + 1 + if self.verifyPoint(im, pix,c[0],c[1] + c[2],False) == -1: + return -2; + if self.verifyPoint(im, pix,c[0],c[1] - c[2],True) == 1: + cardinalpoints = cardinalpoints + 1 + if self.verifyPoint(im, pix,c[0],c[1] - c[2],False) == -1: + return -2; + if cardinalpoints < 3: + return -1; + + for x in imagewidth: + # Pitagora + y = int(round(c[1]- math.sqrt(c[2]**2-(c[0]-x)**2))) + y2= int(round(c[1]+ math.sqrt(c[2]**2-(c[0]-x)**2))) + + howmany = howmany + 2 + if self.verifyPoint(im, pix, x,y,exactfind) == 0: + missing = missing + 1 + missinglist.append((x,y)) + else: + pointsofcircle.append((x,y)) + + if self.verifyPoint(im, pix, x,y,False) == -1: + return -2; + + if self.verifyPoint(im, pix, x,y2,exactfind) == 0: + missing = missing + 1 + missinglist.append((x,y2)) + else: + pointsofcircle.append((x,y2)) + + if self.verifyPoint(im, pix, x,y2,False) == -1: + return -2; + + for y in imageheight: + # Pitagora + x = int(round(c[0]- math.sqrt(c[2]**2-(c[1]-y)**2))) + x2= int(round(c[0]+ math.sqrt(c[2]**2-(c[1]-y)**2))) + + howmany = howmany + 2 + if self.verifyPoint(im, pix, x,y,exactfind) == 0: + missing = missing + 1 + missinglist.append((x,y)) + else: + pointsofcircle.append((x,y)) + + if self.verifyPoint(im, pix, x,y,False) == -1: + return -2; + + if self.verifyPoint(im, pix, x2,y,exactfind) == 0: + missing = missing + 1 + missinglist.append((x2,y)) + else: + pointsofcircle.append((x2,y)) + + if self.verifyPoint(im, pix, x2,y,exactfind) == -1: + return -2; + + for p in missinglist: + # left and bottom + if (self.verifyPoint(im, pix, p[0]-1, p[1],exactfind) == 1 and \ + self.verifyPoint(im, pix, p[0], p[1]+1,exactfind) == 1): + missing = missing - 1 + elif (self.verifyPoint(im, pix, p[0]-1, p[1],exactfind) == 1 and \ + self.verifyPoint(im, pix, p[0], p[1]-1,exactfind) == 1): + missing = missing - 1 + # right and bottom + elif (self.verifyPoint(im, pix, p[0]+1, p[1],exactfind) == 1 and \ + self.verifyPoint(im, pix, p[0], p[1]+1,exactfind) == 1): + missing = missing - 1 + # right and up + elif (self.verifyPoint(im, pix, p[0]+1, p[1],exactfind) == 1 and \ + self.verifyPoint(im, pix, p[0], p[1]-1,exactfind) == 1): + missing = missing - 1 + + if (p[0], p[1]+1) in missinglist or \ + (p[0], p[1]-1) in missinglist or \ + (p[0]+1, p[1]) in missinglist or \ + (p[0]-1, p[1]) in missinglist or \ + (p[0]+1, p[1]+1) in missinglist or \ + (p[0]-1, p[1]+1) in missinglist or \ + (p[0]+1, p[1]-1) in missinglist or \ + (p[0]-1, p[1]-1) in missinglist or \ + self.verifyPoint(im, pix, p[0], p[1],False) == 1: + missingconsecutive = missingconsecutive + 1 + # else: + # pix[p[0], p[1]] = 0 + + if missing / howmany > 0: + indice = c[2] * (missing / howmany) + else: + indice = 0 + + if len(missinglist) > 0: + minX = min(missinglist, key=operator.itemgetter(0))[0] + maxX = max(missinglist, key=operator.itemgetter(0))[0] + + minY = min(missinglist, key=operator.itemgetter(1))[1] + maxY = max(missinglist, key=operator.itemgetter(1))[1] + + # Assial Simmetric + if self._DEBUG == True: + print "Center: " + str(c) + print "Missing: " + str(missing) + print "Howmany: " + str(howmany) + print "Ratio: " + str(missing / howmany) + print "Missing consecutives: " + str(missingconsecutive) + print "Missing X lenght: " + str(minX) + ":" + str(maxX) + print "Missing Y lenght: " + str(minY) + ":" + str(maxY) + print "Ratio without consecutives: " + str((missing - missingconsecutive) / howmany) + print "List missing: " + str(missinglist) + + # Lenght of missing cannot be over 75% of diameter + + if maxX - minX >= c[2] * 2 * 0.75: + return -1; + if maxY - minY >= c[2] * 2 * 0.75: + # raw_input('tro') + return -1; + """ + # Lenght of missing cannot be less 10% of diameter + if maxX - minX < c[2] * 2 * 0.10 and maxY - minY < c[2] * 2 * 0.10: + return -1; + """ + + if missing / howmany > 0.25 or \ + missingconsecutive >= (howmany / 4) * 2 or \ + howmany < 80: + return -1; + # elif missing / howmany < 0.10: + elif missing == 0: + self.pointsofcirclefound.extend(pointsofcircle) + return 1; + elif (missing - missingconsecutive) / howmany < 0.20: + return 0; + else: + self.pointsofcirclefound.extend(pointsofcircle) + return 1; + + + def verifyPoint(self, im, pix, x,y,exact,color = -1): + # Verify point + result = 0 + + if x < 0 or x >= im.size[0]: + return result; + if y < 0 or y >= im.size[1]: + return result; + + curpix = pix[x,y] + if (curpix == color and color > -1) or (curpix < self.BACKGROUND and color == -1): + if curpix > self.BLACKCOLOR: + result = 1 + else: + result = -1 + + # Verify around + if (exact == False): + if x + 1 < im.size[0]: + curpix = pix[x+1,y] + if (curpix == color and color > -1) or (curpix < self.BACKGROUND and color == -1): + if curpix > self.BLACKCOLOR: + result = 1 + if curpix <= self.BLACKCOLOR: + result = -1 + + if x > 0: + curpix = pix[x-1,y] + if (curpix == color and color > -1) or (curpix < self.BACKGROUND and color == -1): + if curpix > self.BLACKCOLOR: + result = 1 + if curpix <= self.BLACKCOLOR: + result = -1 + # print str((x,y)) + " = " + str(result); + return result + + + def decrypt(self, img): + iDebugSaveFile = 0 + mypalette = None + for im in ImageSequence(img): + im.save("orig.png", "png") + if mypalette != None: + im.putpalette(mypalette) + mypalette = im.getpalette() + im = im.convert('L') + + if self._DEBUG == True: + iDebugSaveFile = iDebugSaveFile + 1 + # if iDebugSaveFile < 7: continue; + im.save("output" + str(iDebugSaveFile) + ".png", "png") + raw_input('frame: '+ str(im)) + + pix = im.load() + + stepheight = range(1,im.size[1],2) + # stepheight = range(45,47) + imagewidth = range(1,im.size[0]) + lstPoints = [] # Declares an empty list for the points + lstX = [] # CoordinateX + lstY = [] # CoordinateY + lstColors = [] # Declares an empty list named lst + min_distance = 10 + max_diameter = 70 + + if self._DEBUG == True: + imdebug = im.copy() + draw = ImageDraw.Draw(imdebug) + pixcopy = imdebug.load() + + # Clean image for powerfull search + self.cleanImage(im, pix) + im.save("cleaned" + str(iDebugSaveFile) + ".png", "png") + + found = set() + findnewcircle = True + + # finding all the circles + for y1 in stepheight: + x1 = 1 + curcolor = -1 + for k in range(1,100): + findnewcircle = False + retval = self.findFirstPixelX(im, pix, x1, y1, -1, False) + x1 = retval[0] + curcolor = retval[1] + if x1 == -2: + break; + if x1 == -1: + break; + if self._DEBUG == True: print "x1, y1 -> " + str((x1,y1)) + ": " + str(pix[x1,y1]) + + if (x1,y1) in self.pointsofcirclefound: + if self._DEBUG == True: print 'found ' + str((x1,y1)) + continue; + + if self._DEBUG == True: pixcopy[x1,y1] = 45 #(255,0,0,255) + # found 1 pixel, seeking x2,y2 + x2 = x1 + y2 = y1 + for i in range(1,100): + retval = self.findLastPixelX(im, pix, x2, y2, -1, True) + x2 = retval[0] + if x1 == -2: + findnewcircle = True + break; + if x2 == -1: + break; + if self._DEBUG == True: print "x2, y2 -> " + str((x2,y1)) + ": " + str(pix[x2,y1]) + if abs(x2 - x1) < min_distance: + continue; + if abs(x2 - x1) > (im.size[1] * 2 / 3): + break; + if abs(x2 - x1) > max_diameter: + break; + + if self._DEBUG == True: pixcopy[x2,y2] = 65 #(0,255,0,255) + # found 2 pixel, seeking x3,y3 + # verify cord + + for invert in range(0,2): + x3 = math.floor(x2 - ((x2 - x1) / 2)) + y3 = y1 + for j in range(1,50): + retval = self.findLastPixelY(im, pix, x3, y3, True if invert == 1 else False, -1, True) + # print (x3, y3,retval[0],invert) + y3 = retval[0] + if y3 == -2: + findnewcircle = True + break; + if y3 == -1: + break; + + if self._DEBUG == True: print "x3, y3 -> " + str((x3,y3)) + ": " + str(pix[x3,y3]) + # verify cord + if abs(y3 - y2) < min_distance: + continue; + if abs(y3 - y2) > (im.size[1] * 2 / 3): + break; + if abs(y3 - y2) > max_diameter: + break; + + if self._DEBUG == True: pixcopy[x3,y3] = 85 + # found 3 pixel. try circle + c = self.findCircle(pix, x1,y1,x2,y2,x3,y3) + + if c[0] + c[2] >= im.size[0] or c[1] + c[2] >= im.size[1] or c[0] - c[2] <= 0 or c[1] - c[2] <= 0: + continue; + + if self._DEBUG == True: pixcopy[c[0],c[1]] = 0 + # (x-r, y-r, x+r, y+r) + verified = self.verifyCircle(im, pix, c) + + if verified == -1: + verified = -1 + elif verified == 0: + found.add(((c[0],c[1],c[2]),verified)) + findnewcircle = True + elif verified == 1: + found.add(((c[0],c[1],c[2]),verified)) + findnewcircle = True + + if self._DEBUG == True: + _pause = "" + # if verified == -1: + # draw.ellipse((c[0]-c[2],c[1]-c[2],c[0]+c[2],c[1]+c[2]),outline=0) + # _pause = "NOTDOUND" + # imdebug.save("debug.png", "png") + if verified == 0: + draw.ellipse((c[0]-c[2],c[1]-c[2],c[0]+c[2],c[1]+c[2]),outline=120) + _pause = "OPENED" + + if verified == 1: + draw.ellipse((c[0]-c[2],c[1]-c[2],c[0]+c[2],c[1]+c[2]),outline=65) + _pause = "CLOSED" + + imdebug.save("debug.png", "png") + + if _pause != "": + valore = raw_input('Found ' + _pause + ' CIRCLE circle press [Enter] = continue / [q] for Quit: ' + str(verified)) + if valore == 'q': + sys.exit(); + + if findnewcircle == True: + break; + if findnewcircle == True: + break; + if findnewcircle == True: + break; + + if self._DEBUG == True: + print 'Howmany opened circle? ' + str(len(found)) + ' ' + str(found) + + # clean results + for c in found: + verify = c[1] + if verify == 0: + p = c[0] + if ( + ((p[0], p[1]+1,p[2]),1) in found or \ + ((p[0], p[1]-1,p[2]),1) in found or \ + ((p[0]+1, p[1],p[2]),1) in found or \ + ((p[0]-1, p[1],p[2]),1) in found or \ + ((p[0]+1, p[1]+1,p[2]),1) in found or \ + ((p[0]-1, p[1]+1,p[2]),1) in found or \ + ((p[0]+1, p[1]-1,p[2]),1) in found or \ + ((p[0]-1, p[1]-1,p[2]),1) in found \ + ): + + # delete nearly circle + verify = -1 + if ( + ((p[0], p[1]+1,p[2]+1),1) in found or \ + ((p[0], p[1]-1,p[2]+1),1) in found or \ + ((p[0]+1, p[1],p[2]+1),1) in found or \ + ((p[0]-1, p[1],p[2]+1),1) in found or \ + ((p[0]+1, p[1]+1,p[2]+1),1) in found or \ + ((p[0]-1, p[1]+1,p[2]+1),1) in found or \ + ((p[0]+1, p[1]-1,p[2]+1),1) in found or \ + ((p[0]-1, p[1]-1,p[2]+1),1) in found \ + ): + + # delete nearly circle + verify = -1 + if ( + ((p[0], p[1]+1,p[2]-1),1) in found or \ + ((p[0], p[1]-1,p[2]-1),1) in found or \ + ((p[0]+1, p[1],p[2]-1),1) in found or \ + ((p[0]-1, p[1],p[2]-1),1) in found or \ + ((p[0]+1, p[1]+1,p[2]-1),1) in found or \ + ((p[0]-1, p[1]+1,p[2]-1),1) in found or \ + ((p[0]+1, p[1]-1,p[2]-1),1) in found or \ + ((p[0]-1, p[1]-1,p[2]-1),1) in found \ + ): + + # delete nearly circle + verify = -1 + + # if verify == 0: + # if self._DEBUG == True: + # pix[c[0][0],c[0][1]] = 90 #(255,255,0) + # im.save("output.png", "png") + # return c[0][0],c[0][1] + # elif verify == 1: + # if self._DEBUG == True: + # pix[c[0][0],c[0][1]] = 40 #(255,0,0) + # im.save("output.png", "png") + # else: + # if self._DEBUG == True: + # pix[c[0][0],c[0][1]] = 180 #(0,0,255) + # im.save("output.png", "png") + + if self._DEBUG == True: + im.save("output.png", "png") + + + # Return coordinates of opened circle (eg (x,y)) + def decrypt_from_web(self, url): + file = cStringIO.StringIO(urllib.urlopen(url).read()) + img = Image.open(file) + coords = self.decrypt(img); + print "Coords: " + str(coords) + + + # Return coordinates of opened circle (eg (x,y)) + def decrypt_from_file(self, filename): + coords = self.decrypt(Image.open(filename)); #Can be many different formats. + print "Coords: " + str(coords) + + +##DEBUG +# import datetime +# a = datetime.datetime.now() +# x = CircleCaptcha() +# coords = x.decrypt_from_file("decripter/captx.html2.gif") +# coords = x.decrypt_from_web("http://ncrypt.in/classes/captcha/circlecaptcha.php") +# b = datetime.datetime.now() +# print 'Elapsed time: ' + str((b-a).seconds) + ' seconds' -- cgit v1.2.3