python类open()的实例源码

single_iamge.py 文件源码 项目:FCN_train 作者: 315386775 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def  convert(width,height):
    im = Image.open("C:\\xxx\\test.jpg")
    out = im.resize((width, height),Image.ANTIALIAS)
    out.save("C:\\xxx\\test.jpg")
caves.py 文件源码 项目:caves 作者: mikaelho 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def play(self, sender):
#    self.mode = console.alert('Race mode',
#      button1='1. Blind draw',
#      button2='2. Timed vectors'
#    )
    self.hide_all()
    #self.show_play_menu() dialog
    self.show_edit_view()
    self.load_actual(burn_waypoints_in=True)

    with io.BytesIO(self.edit_view.img.to_png()) as fp:
      playfield = pilImage.open(fp).resize((int(self.bg.width), int(self.bg.height))).load()
    for layer in self.play_layers:
      layer.set_map(self.edit_view.waypoints, playfield, self.multiplier)
    self.show_play_layers()
    self.turn = -1
    self.next_turn()
textures.py 文件源码 项目:CC3501-2017-1 作者: ppizarror 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def load_texture(image_file, repeat=False):
    """Carga una textura desde un archivo image_file"""
    img = Image.open(image_file)
    data = numpy.array(list(img.getdata()), numpy.int8)

    tex = glGenTextures(1)
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
    glBindTexture(GL_TEXTURE_2D, tex)

    if repeat:
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
    else:
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP)

    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img.size[0], img.size[1], 0, GL_RGB, GL_UNSIGNED_BYTE, data)
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE)
    return tex
colors.py 文件源码 项目:iutils 作者: inconvergent 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def get_colors(f, do_shuffle=True):
  try:
    import Image
  except Exception:
    from PIL import Image

  scale = 1./255.
  im = Image.open(f)
  data = list(im.convert('RGB').getdata())

  res = []
  for r,g,b in data:
    res.append([r*scale,g*scale,b*scale])

  if do_shuffle:
    from numpy.random import shuffle
    shuffle(res)

  return res
render.py 文件源码 项目:iutils 作者: inconvergent 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def get_colors_from_file(self, fn):

    import Image
    from numpy.random import shuffle

    def p(f):
      return float('{:0.5f}'.format(f))

    scale = 1./255.
    im = Image.open(fn)
    w, h = im.size
    rgbim = im.convert('RGB')
    res = []
    for i in range(0, w):
      for j in range(0, h):
        r, g, b = rgbim.getpixel((i, j))
        res.append([p(r*scale), p(g*scale), p(b*scale)])

    shuffle(res)

    self.colors = res
    self.ncolors = len(res)
mets_to_iiif.py 文件源码 项目:mets2man 作者: thegetty 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def create_thumb(img_name):
    image = Image.open('{}.tiff'.format(img_name))
    (imageW, imageH) = image.size
    if imageW > imageH:
        ratio = thumb_size / imageW
        newWidth = 400
        newHeight = int(imageH * ratio)
    else:
        ratio = thumb_size / imageH
        newHeight = 400
        newWidth = int(imageW * ratio)  

    image = image.resize((newWidth, newHeight), Image.LANCZOS)
    outfh = open('{}_thumb.tiff'.format(img_name), 'wb')
    image.save(outfh, format='TIFF')
    outfh.close()
forms.py 文件源码 项目:DCRM 作者: 82Flex 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def clean_zip_file(self):
        """Open the zip file a first time, to check that it is a valid zip archive.
        We'll open it again in a moment, so we have some duplication, but let's focus
        on keeping the code easier to read!
        """
        zip_file = self.cleaned_data['zip_file']
        try:
            zip = zipfile.ZipFile(zip_file)
        except BadZipFile as e:
            raise forms.ValidationError(str(e))
        bad_file = zip.testzip()
        if bad_file:
            zip.close()
            raise forms.ValidationError('"%s" in the .zip archive is corrupt.' % bad_file)
        zip.close()  # Close file in all cases.
        return zip_file
gen_rst.py 文件源码 项目:sequana 作者: sequana 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def check_md5sum_change(src_file):
    """Returns True if src_file has a different md5sum"""

    src_md5 = get_md5sum(src_file)

    src_md5_file = src_file + '.md5'
    src_file_changed = True
    if os.path.exists(src_md5_file):
        with open(src_md5_file, 'r') as file_checksum:
            ref_md5 = file_checksum.read()
        if src_md5 == ref_md5:
            src_file_changed = False

    if src_file_changed:
        with open(src_md5_file, 'w') as file_checksum:
            file_checksum.write(src_md5)

    return src_file_changed
pytesser.py 文件源码 项目:base_function 作者: Rockyzsu 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def image_file_to_string(filename, cleanup = cleanup_scratch_flag, graceful_errors=True):
    """Applies tesseract to filename; or, if image is incompatible and graceful_errors=True,
    converts to compatible format and then applies tesseract.  Fetches resulting text.
    If cleanup=True, delete scratch files after operation."""
    try:
        try:
            call_tesseract(filename, scratch_text_name_root)
            text = util.retrieve_text(scratch_text_name_root)
        except errors.Tesser_General_Exception:
            if graceful_errors:
                im = Image.open(filename)
                text = image_to_string(im, cleanup)
            else:
                raise
    finally:
        if cleanup:
            util.perform_cleanup(scratch_image_name, scratch_text_name_root)
    return text
main.py 文件源码 项目:Nightchord 作者: theriley106 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def genLines(image=None):
    PrintGood('This is going to return OCR on either a list of images or full images')
    if isinstance(image, list) == False:
        image = PromptList('Which image/images to OCR: ', image)
    Found = []
    for image in image:
        image = Image.open(image)
        with PyTessBaseAPI() as api:
            api.SetImage(image)
            boxes = api.GetComponentImages(RIL.TEXTLINE, True)
            print 'Found {} textline image components.'.format(len(boxes))
            for i, (im, box, _, _) in enumerate(boxes):
                # im is a PIL image object
                # box is a dict with x, y, w and h keys
                api.SetRectangle(box['x'], box['y'], box['w'], box['h'])
                ocrResult = api.GetUTF8Text().split(' ')
                conf = api.MeanTextConf()
                ocrResult = [word.strip() for word in ocrResult]
                Found.append(ocrResult)
                print (u"Box[{0}]: x={x}, y={y}, w={w}, h={h}, "
                       "confidence: {1}, text: {2}").format(i, conf, ocrResult, **box)
    return Found
main.py 文件源码 项目:Nightchord 作者: theriley106 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def Spaces(image=None):
    PrintGood('This returns the number of spaces in a specific image or images')
    if isinstance(image, list) == False:
        image = PromptList('Which image/images to Scan: ', image)
    for image in image:
        image = Image.open(image)
        with PyTessBaseAPI() as api:
            api.SetImage(image)
            boxes = api.GetComponentImages(RIL.TEXTLINE, True)
            Spaces = 0
            for i, (im, box, _, _) in enumerate(boxes):
                im.save('saving{}.jpg'.format(i))
                api.SetRectangle(box['x'], box['y'], box['w'], box['h'])
                ocrResult = api.GetUTF8Text()
                conf = api.MeanTextConf()
                text = str(ocrResult).replace('\n', '').split(' ')
                Spaces = len(text) + Spaces
    return int(Spaces)
main.py 文件源码 项目:Nightchord 作者: theriley106 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def ocrToDict(image=None, listofwords=[]):
    #image can be a list of files
    Words = {}
    if len(listofwords) == 0:
        PrintFail('You need to input a list of words')
        if 'y' in str(raw_input("Do you want to search for lyrics now? ")).lower():
            artist = raw_input("Artist: ")
            song = raw_input("Song: ")
            listofwords = GrabSongLyrics(artist, song)
            print(listofwords)
        else:
            return
    if isinstance(image, list) == False:
        image = PromptList('Which image/images to Scan: ', image)
    for i, image in enumerate(image):
        Words['Clean'][i] = imageToOCR(image, listofwords)
    with open('{}Transcript.json'.format(Words[1]), 'w') as f:
        json.dump(Words, f)
main.py 文件源码 项目:Nightchord 作者: theriley106 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def WriteToImage(output, txt, size=45, input='background.jpg'):
    output = str(output).replace('.png', '').replace('.jpg', '')
    i = Image.open(input)
    font = ImageFont.load_default()
    txt = txt.split(' ')
    r = []
    for part in txt:
        r.append(str(part).replace(' ', ''))
    txt = r
    a = ''
    while len(txt) > 0:
        try:
            for e in range(7):
                item = txt[0]
                txt.remove(item)
                a = a + ' ' + str(item)
            a = a + '\n'
        except:
            break
    text_col = (255, 255, 255) # bright green
    halo_col = (0, 0, 0)   # black
    i2 = draw_text_with_halo(i, (20, 40), a, font, text_col, halo_col)
    i2.save('{}.png'.format(output))
steganography.py 文件源码 项目:Steganography 作者: cristian-henrique 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def insert_text(img, dest, msg):
    image = Image.open(img)
    width, height = image.size

    if image.mode[:3] != "RGB" or width * height * 3 < len(msg) + RESERVED_PIXELS * 3:
        raise IndexError("Unable to use this picture")

    bits = bin(len(msg))[2:].zfill(RESERVED_PIXELS * 3)
    msg = bits + msg

    msg = enumerate(msg + "0" * (3 - len(msg) % 3))
    p = image.load()

    for i, j in pixels(image.size):
        try:
            rgb = map(lambda color, bit: color - (color % 2) + int(bit), p[i, j][:3], [msg.next()[1] for _ in xrange(3)])
            p[i, j] = tuple(rgb)
        except StopIteration:
            image.save(dest, "PNG", quality = 100)
            return
steganography.py 文件源码 项目:Steganography 作者: cristian-henrique 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def extract_text(img):
    image = Image.open(img)
    length = image.size
    p = image.load()

    leng = ""
    for pix in pixels(length):
        leng += "".join("1" if color % 2 else "0" for color in p[pix][:3])
        if len(leng) >= RESERVED_PIXELS * 3:
            leng = int(leng, 2)
            break

    binary_information = ""
    for pix in pixels(length):
        binary_information += "".join("1" if color % 2 else "0" for color in p[pix][:3])

    return binary_information[RESERVED_PIXELS * 3 : leng + RESERVED_PIXELS * 3]
__init__.py 文件源码 项目:sphinx-nbexamples 作者: Chilipp 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def create_py(self, nb, force=False):
        """Create the python script from the notebook node"""
        # Although we would love to simply use ``nbconvert.export_python(nb)``
        # this causes troubles in other cells processed by the ipython
        # directive. Instead of getting something like ``Out [5]:``, we get
        # some weird like '[0;31mOut[[1;31m5[0;31m]: [0m' which look like
        # color information if we allow the call of nbconvert.export_python
        if list(map(int, re.findall('\d+', nbconvert.__version__))) >= [4, 2]:
            py_file = os.path.basename(self.py_file)
        else:
            py_file = self.py_file
        spr.call(['jupyter', 'nbconvert', '--to=python',
                  '--output=' + py_file, '--log-level=%s' % logger.level,
                  self.outfile])
        with open(self.py_file) as f:
            py_content = f.read()
        # comment out ipython magics
        py_content = re.sub('^\s*get_ipython\(\).magic.*', '# \g<0>',
                            py_content, flags=re.MULTILINE)
        with open(self.py_file, 'w') as f:
            f.write(py_content)
fpdf.py 文件源码 项目:true_review_web2py 作者: lucadealfaro 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def _parsejpg(self, filename):
        # Extract info from a JPEG file
        if Image is None:
            self.error('PIL not installed')
        try:
            f = open(filename, 'rb')
            im = Image.open(f)
        except Exception, e:
            self.error('Missing or incorrect image file: %s. error: %s' % (filename, str(e)))
        else:
            a = im.size
        # We shouldn't get into here, as Jpeg is RGB=8bpp right(?), but, just in case...
        bpc=8
        if im.mode == 'RGB':
            colspace='DeviceRGB'
        elif im.mode == 'CMYK':
            colspace='DeviceCMYK'
        else:
            colspace='DeviceGray'

        # Read whole file from the start
        f.seek(0)
        data = f.read()
        f.close()
        return {'w':a[0],'h':a[1],'cs':colspace,'bpc':bpc,'f':'DCTDecode','data':data}
fpdf.py 文件源码 项目:true_review_web2py 作者: lucadealfaro 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def _parsegif(self, filename):
        # Extract info from a GIF file (via PNG conversion)
        if Image is None:
            self.error('PIL is required for GIF support')
        try:
            im = Image.open(filename)
        except Exception, e:
            self.error('Missing or incorrect image file: %s. error: %s' % (filename, str(e)))
        else:
            # Use temporary file
            f = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
            tmp = f.name
            f.close()
            if "transparency" in im.info:
                im.save(tmp, transparency = im.info['transparency'])
            else:
                im.save(tmp)
            info = self._parsepng(tmp)
            os.unlink(tmp)
        return info
NOTWORKING_hellovr_opengl_sdl.py 文件源码 项目:pyopenvr 作者: cmbruns 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def setupTexturemaps(self):
        this_folder = os.path.dirname(os.path.abspath(__file__))
        image_path = os.path.join(this_folder, "cube_texture_small.png")
        img = Image.open(image_path)
        imageRGBA = numpy.array(list(img.getdata()), numpy.uint8)
        self.m_iTexture = glGenTextures(1)
        glBindTexture( GL_TEXTURE_2D, self.m_iTexture )
        glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, img.size[0], img.size[1],
            0, GL_RGB, GL_UNSIGNED_BYTE, imageRGBA )
        glGenerateMipmap(GL_TEXTURE_2D)
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE )
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE )
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR )
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR )
        fLargest = glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, fLargest)
        glBindTexture( GL_TEXTURE_2D, 0 )
        return self.m_iTexture != 0
fpdf.py 文件源码 项目:spc 作者: whbrewer 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def _parsejpg(self, filename):
        # Extract info from a JPEG file
        if Image is None:
            self.error('PIL not installed')
        try:
            f = open(filename, 'rb')
            im = Image.open(f)
        except Exception, e:
            self.error('Missing or incorrect image file: %s. error: %s' % (filename, str(e)))
        else:
            a = im.size
        # We shouldn't get into here, as Jpeg is RGB=8bpp right(?), but, just in case...
        bpc=8
        if im.mode == 'RGB':
            colspace='DeviceRGB'
        elif im.mode == 'CMYK':
            colspace='DeviceCMYK'
        else:
            colspace='DeviceGray'

        # Read whole file from the start
        f.seek(0)
        data = f.read()
        f.close()
        return {'w':a[0],'h':a[1],'cs':colspace,'bpc':bpc,'f':'DCTDecode','data':data}
fpdf.py 文件源码 项目:spc 作者: whbrewer 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def _parsegif(self, filename):
        # Extract info from a GIF file (via PNG conversion)
        if Image is None:
            self.error('PIL is required for GIF support')
        try:
            im = Image.open(filename)
        except Exception, e:
            self.error('Missing or incorrect image file: %s. error: %s' % (filename, str(e)))
        else:
            # Use temporary file
            f = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
            tmp = f.name
            f.close()
            if "transparency" in im.info:
                im.save(tmp, transparency = im.info['transparency'])
            else:
                im.save(tmp)
            info = self._parsepng(tmp)
            os.unlink(tmp)
        return info
gen_rst.py 文件源码 项目:scipy-lecture-notes-zh-CN 作者: jayleicn 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def _get_data(url):
    """Helper function to get data over http or from a local file"""
    if url.startswith('http://'):
        resp = urllib2.urlopen(url)
        encoding = resp.headers.dict.get('content-encoding', 'plain')
        data = resp.read()
        if encoding == 'plain':
            pass
        elif encoding == 'gzip':
            data = StringIO(data)
            data = gzip.GzipFile(fileobj=data).read()
        else:
            raise RuntimeError('unknown encoding')
    else:
        with open(url, 'r') as fid:
            data = fid.read()
        fid.close()

    return data
qrtools.py 文件源码 项目:qrtools 作者: primetang 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def decode(self, filename=None):
        self.filename = filename or self.filename
        if self.filename:
            scanner = zbar.ImageScanner()
            # configure the reader
            scanner.parse_config('enable')
            # obtain image data
            pil = Image.open(self.filename).convert('L')
            width, height = pil.size
            try:
                raw = pil.tobytes()
            except AttributeError:
                raw = pil.tostring()
            # wrap image data
            image = zbar.Image(width, height, 'Y800', raw)
            # scan the image for barcodes
            result = scanner.scan(image)
            # extract results
            if result == 0:
                return False
            else:
                for symbol in image:
                    pass
                # clean up
                del(image)
                # Assuming data is encoded in utf8
                self.data = symbol.data.decode(u'utf-8')
                self.data_type = self.data_recognise()
                return True
        else:
            return False
fpdf.py 文件源码 项目:Problematica-public 作者: TechMaz 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def _parsejpg(self, filename):
        # Extract info from a JPEG file
        if Image is None:
            self.error('PIL not installed')
        try:
            f = open(filename, 'rb')
            im = Image.open(f)
        except Exception, e:
            self.error('Missing or incorrect image file: %s. error: %s' % (filename, str(e)))
        else:
            a = im.size
        # We shouldn't get into here, as Jpeg is RGB=8bpp right(?), but, just in case...
        bpc=8
        if im.mode == 'RGB':
            colspace='DeviceRGB'
        elif im.mode == 'CMYK':
            colspace='DeviceCMYK'
        else:
            colspace='DeviceGray'

        # Read whole file from the start
        f.seek(0)
        data = f.read()
        f.close()
        return {'w':a[0],'h':a[1],'cs':colspace,'bpc':bpc,'f':'DCTDecode','data':data}
fpdf.py 文件源码 项目:Problematica-public 作者: TechMaz 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def _parsegif(self, filename):
        # Extract info from a GIF file (via PNG conversion)
        if Image is None:
            self.error('PIL is required for GIF support')
        try:
            im = Image.open(filename)
        except Exception, e:
            self.error('Missing or incorrect image file: %s. error: %s' % (filename, str(e)))
        else:
            # Use temporary file
            f = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
            tmp = f.name
            f.close()
            if "transparency" in im.info:
                im.save(tmp, transparency = im.info['transparency'])
            else:
                im.save(tmp)
            info = self._parsepng(tmp)
            os.unlink(tmp)
        return info
helpers.py 文件源码 项目:sand-spline 作者: inconvergent 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def get_colors(f, do_shuffle=True):
  from numpy import array
  try:
    import Image
  except Exception:
    from PIL import Image

  im = Image.open(f)
  data = array(list(im.convert('RGB').getdata()),'float')/255.0

  res = []
  for rgb in data:
    res.append(list(rgb))

  if do_shuffle:
    from numpy.random import shuffle
    shuffle(res)
  return res
distinguish.py 文件源码 项目:SeuBooking_v0 作者: 2Hurric 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def binary(f):                #????????
    print f
    img = Image.open(f)
    #img = img.convert('1')
    img = img.convert("RGBA")  #???????????????????
    pixdata = img.load()
    for y in xrange(img.size[1]):
        for x in xrange(img.size[0]):
            if pixdata[x, y][0] < 90:
                pixdata[x, y] = (0, 0, 0, 255)
    for y in xrange(img.size[1]):
        for x in xrange(img.size[0]):
            if pixdata[x, y][1] < 136:
                pixdata[x, y] = (0, 0, 0, 255)
    for y in xrange(img.size[1]):
        for x in xrange(img.size[0]):
            if pixdata[x, y][2] > 0:
                pixdata[x, y] = (255, 255, 255, 255)
    return img
gen_rst.py 文件源码 项目:dyfunconn 作者: makism 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def _get_data(url):
    """Helper function to get data over http or from a local file"""
    if url.startswith('http://'):
        # Try Python 2, use Python 3 on exception
        try:
            resp = urllib.urlopen(url)
            encoding = resp.headers.dict.get('content-encoding', 'plain')
        except AttributeError:
            resp = urllib.request.urlopen(url)
            encoding = resp.headers.get('content-encoding', 'plain')
        data = resp.read()
        if encoding == 'plain':
            pass
        elif encoding == 'gzip':
            data = StringIO(data)
            data = gzip.GzipFile(fileobj=data).read()
        else:
            raise RuntimeError('unknown encoding')
    else:
        with open(url, 'r') as fid:
            data = fid.read()
        fid.close()

    return data
gen_rst.py 文件源码 项目:dyfunconn 作者: makism 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def extract_line_count(filename, target_dir):
    # Extract the line count of a file
    example_file = os.path.join(target_dir, filename)
    lines = open(example_file).readlines()
    start_row = 0
    if lines and lines[0].startswith('#!'):
        lines.pop(0)
        start_row = 1
    line_iterator = iter(lines)
    tokens = tokenize.generate_tokens(lambda: next(line_iterator))
    check_docstring = True
    erow_docstring = 0
    for tok_type, _, _, (erow, _), _ in tokens:
        tok_type = token.tok_name[tok_type]
        if tok_type in ('NEWLINE', 'COMMENT', 'NL', 'INDENT', 'DEDENT'):
            continue
        elif (tok_type == 'STRING') and check_docstring:
            erow_docstring = erow
            check_docstring = False
    return erow_docstring + 1 + start_row, erow + 1 + start_row
LinksaveIn.py 文件源码 项目:download-manager 作者: thispc 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def substract_bg(self, bgpath):
        bg = Image.open(bgpath)
        img = self.img.convert("P")

        bglut = bg.resize((256, 1))
        bglut.putdata(range(256))
        bglut = list(bglut.convert("RGB").getdata())

        lut = img.resize((256, 1))
        lut.putdata(range(256))
        lut = list(lut.convert("RGB").getdata())

        bgpix = bg.load()
        pix = img.load()
        orgpix = self.img.load()
        for x in range(bg.size[0]):
            for y in range(bg.size[1]):
                rgb_bg = bglut[bgpix[x, y]]
                rgb_c = lut[pix[x, y]]
                if rgb_c == rgb_bg:
                    orgpix[x, y] = (255, 255, 255)


问题


面经


文章

微信
公众号

扫码关注公众号