Пример #1
1
    def _open(self):

        # Screen
        s = self.fp.read(13)
        if s[:6] not in ["GIF87a", "GIF89a"]:
            raise SyntaxError, "not a GIF file"

        self.info["version"] = s[:6]

        self.size = i16(s[6:]), i16(s[8:])

        self.tile = []

        flags = ord(s[10])

        bits = (flags & 7) + 1

        if flags & 128:
            # get global palette
            self.info["background"] = ord(s[11])
            # check if palette contains colour indices
            p = self.fp.read(3 << bits)
            for i in range(0, len(p), 3):
                if not (chr(i / 3) == p[i] == p[i + 1] == p[i + 2]):
                    p = ImagePalette.raw("RGB", p)
                    self.global_palette = self.palette = p
                    break

        self.__fp = self.fp  # FIXME: hack
        self.__rewind = self.fp.tell()
        self.seek(0)  # get ready to read first frame
def _obfuscate(name, key):
    if name is None:
        return ''
    s = []
    for i in range(len(name)):
        s.append(chr(ord(name[i]) ^ ord(key[i % 13])))
    return base64.b64encode(''.join(s))
Пример #3
0
    def _escape_text(self, text):
        # empty strings, should give a small performance improvment
        if not text:
            return ''

        # escape text
        text = self._escape(text)
        if self.encoding in ('utf-8', 'utf-16', 'utf-32'):
            encoding = 'iso-8859-15'
        else:
            encoding = self.encoding or 'iso-8859-15'

        buf = []
        for c in text:
            if ord(c) > 128:
                ansic = c.encode(encoding, 'ignore') or '?'
                if ord(ansic) > 128:
                    ansic = '\\\'%x' % ord(ansic)
                else:
                    ansic = c
                buf.append(r'\ud{\u%d%s}' % (ord(c), ansic))
            else:
                buf.append(str(c))

        return ''.join(buf).replace('\n', '\\par\n')
Пример #4
0
def encode_pinyin(pinyin):
    if pinyin == None or pinyin == "":
        return 0
    e = 0
    for c in pinyin:
        e = (e << 5) + (ord(c) - ord('a') + 1)
    return e
Пример #5
0
def decode_pair(s, pos=0):
    """
    Decodes a name/value pair.

    The number of bytes decoded as well as the name/value pair
    are returned.
    """
    nameLength = ord(s[pos])
    if nameLength & 128:
        nameLength = struct.unpack('!L', s[pos:pos+4])[0] & 0x7fffffff
        pos += 4
    else:
        pos += 1

    valueLength = ord(s[pos])
    if valueLength & 128:
        valueLength = struct.unpack('!L', s[pos:pos+4])[0] & 0x7fffffff
        pos += 4
    else:
        pos += 1

    name = s[pos:pos+nameLength]
    pos += nameLength
    value = s[pos:pos+valueLength]
    pos += valueLength

    return (pos, (name, value))
Пример #6
0
 def __init__(self, screen, args):
     self.log = logging.getLogger(__name__)
     self.log.debug("Initializing screen.")
     self.args = args
     self.interactive = not args.non_interactive
     if self.interactive:
         res, ret = unicurses.KEY_RESIZE, unicurses.KEY_ENTER
         self.ctrlchars = (res, ret, ord('\n'), ord('\x1b'))
         self.msg = None
         self.screen = screen
         self.h, self.w = 22, 78
         self.wrap = textwrap.TextWrapper(width=self.w - 1)
         self.initattrs()
         self.frame = unicurses.newwin(self.h + 2, self.w + 2, 0, 0)
         unicurses.wborder(self.frame)
         self.win = unicurses.newwin(self.h, self.w, 0, 0)
         unicurses.keypad(self.win, 1)
     self.sslnoverify = sys.version_info >= (2, 7, 9) and args.ssl_no_verify
     self.loadst, self.savest = True, True
     self.state = DataTree(self, {})
     self.oldstate = DataTree(self, {})
     self.validate = Validate(self)
     self.format = Format(self)
     self.nexus = Nexus(self)
     self.artifactory = Artifactory(self)
     self.initstate(args.load_file)
     self.log.debug("Screen initialized.")
Пример #7
0
def check_key(key, key_extra_len=0):
    """Checks sanity of key.  Fails if:
        Key length is > SERVER_MAX_KEY_LENGTH (Raises MemcachedKeyLength).
        Contains control characters  (Raises MemcachedKeyCharacterError).
        Is not a string (Raises MemcachedStringEncodingError)
        Is an unicode string (Raises MemcachedStringEncodingError)
        Is not a string (Raises MemcachedKeyError)
        Is None (Raises MemcachedKeyError)
    """

    return # Short-circuit this expensive method

    if type(key) == types.TupleType: key = key[1]
    if not key:
        raise Client.MemcachedKeyNoneError, ("Key is None")
    if isinstance(key, unicode):
        raise Client.MemcachedStringEncodingError, ("Keys must be str()'s, not "
                "unicode.  Convert your unicode strings using "
                "mystring.encode(charset)!")
    if not isinstance(key, str):
        raise Client.MemcachedKeyTypeError, ("Key must be str()'s")

    if isinstance(key, basestring):
        if len(key) + key_extra_len > SERVER_MAX_KEY_LENGTH:
             raise Client.MemcachedKeyLengthError, ("Key length is > %s"
                     % SERVER_MAX_KEY_LENGTH)
        for char in key:
            if ord(char) < 32 or ord(char) == 127:
                raise Client.MemcachedKeyCharacterError, "Control characters not allowed"
Пример #8
0
    def AppendToFile(self, filename, n_line_breaks=0):
        '''Appends user-friendly description of this time result object to
           a specified text file. If line breaks are desired, they will be
           appended to the file before the data.'''
        # Guard conditions
        if n_line_breaks < 0:
            n_line_breaks = 0
        
        # Open binary file in append mode
        filehandler = OpenAppendByteDataFile(filename)

        # If line breaks are desired, append them before the data
        lineBreak = tuple(os.linesep)
        if n_line_breaks > 0:
            lineBreakBytes = bytearray()
            for i in range(n_line_breaks):
                lineBreakBytes.extend(ord(char) for char in lineBreak)
            filehandler.write(lineBreakBytes)
        
        # Append byte format of string representation of self to file
        filehandler.write(bytes(str(self).encode("utf-8")))

        # Insert a newline to prepare for readable format considering future
        # data appending
        filehandler.write(bytearray(ord(char) for char in lineBreak))

        # Close file
        filehandler.close()
Пример #9
0
 def getSizeOfTrailingDataEntry(data):
         num = 0
         for v in data[-4:]:
                 if ord(v) & 0x80:
                         num = 0
                 num = (num << 7) | (ord(v) & 0x7f)
         return num
Пример #10
0
def _netbios_getnode():
    """Get the hardware address on Windows using NetBIOS calls.
    See http://support.microsoft.com/kb/118623 for details."""
    import win32wnet, netbios
    ncb = netbios.NCB()
    ncb.Command = netbios.NCBENUM
    ncb.Buffer = adapters = netbios.LANA_ENUM()
    adapters._pack()
    if win32wnet.Netbios(ncb) != 0:
        return
    adapters._unpack()
    for i in range(adapters.length):
        ncb.Reset()
        ncb.Command = netbios.NCBRESET
        ncb.Lana_num = ord(adapters.lana[i])
        if win32wnet.Netbios(ncb) != 0:
            continue
        ncb.Reset()
        ncb.Command = netbios.NCBASTAT
        ncb.Lana_num = ord(adapters.lana[i])
        ncb.Callname = '*'.ljust(16)
        ncb.Buffer = status = netbios.ADAPTER_STATUS()
        if win32wnet.Netbios(ncb) != 0:
            continue
        status._unpack()
        bytes = map(ord, status.adapter_address)
        return ((bytes[0]<<40L) + (bytes[1]<<32L) + (bytes[2]<<24L) +
                (bytes[3]<<16L) + (bytes[4]<<8L) + bytes[5])
Пример #11
0
def single_block_test_sha512x(block, mode, ser):
    # Write block to SHA-512.
    for i in range(len(block) / 4):
        message = [SOC, WRITE_CMD, SHA512_ADDR_PREFIX,] + [sha512_block_addr[i]] +\
                  block[(i * 4) : ((i * 4 ) + 4)] + [EOC]
        write_serial_bytes(message, ser)

    # Start initial block hashing, wait and check status.
    mode_cmd = chr(ord(SHA512_CTRL_INIT_CMD) + (ord(mode) << SHA512_CTRL_MODE_LOW))
    write_serial_bytes([SOC, WRITE_CMD, SHA512_ADDR_PREFIX, SHA512_ADDR_CTRL,
                        '\x00', '\x00', '\x00', mode_cmd, EOC], ser)
    time.sleep(PROC_DELAY_TIME)
    write_serial_bytes([SOC, READ_CMD, SHA512_ADDR_PREFIX, SHA512_ADDR_STATUS, EOC], ser)

    # Select the correct number of digest addresses to read.
    if (mode == MODE_SHA_512_224):
        mode_digest_addr = sha512_digest_addr[0 : 7]
    elif (mode == MODE_SHA_512_256):
        mode_digest_addr = sha512_digest_addr[0 : 8]
    elif (mode == MODE_SHA_384):
        mode_digest_addr = sha512_digest_addr[0 : 12]
    elif (mode == MODE_SHA_512):
        mode_digest_addr = sha512_digest_addr

    # Extract the digest.
    for digest_addr in mode_digest_addr:
        message = [SOC, READ_CMD, SHA512_ADDR_PREFIX] + [digest_addr] + [EOC]
        write_serial_bytes(message, ser)
    print""
Пример #12
0
def main(verbose=False):
    message = get_data(59).split(',')

    message = [int(char) for char in message]

    possible_keys = []
    for ascii1 in range(97, 123):
        for ascii2 in range(97, 123):
            for ascii3 in range(97, 123):
                possible_keys.append([ascii1, ascii2, ascii3])

    for key in possible_keys:
        curr = translate(message, key)
        if (curr.upper().find('THE') != -1
                and curr.upper().find('IS') != -1
                and curr.upper().find('AND') != -1
                and curr.upper().find('OF') != -1
                and curr.upper().find('ARE') != -1):
            break

    key_as_word = ''.join(chr(val) for val in key)
    result = '\n\nActual Message:\n%s\n\nThe key is: %s or %s.' % (
        curr, key_as_word, key)

    if verbose:
        return '%s%s' % (sum(ord(letter) for letter in curr), result)
    else:
        return sum(ord(letter) for letter in curr)
Пример #13
0
def getTranslatedMessage(mode, message, key):
    if mode[0] == 'd':
        key = -key
    translated = ''

    for symbol in message:
        if symbol.isalpha():
            num = ord(symbol)
            num += key

            if symbol.isupper():
                if num > ord('Z'):
                    num -= 26
                elif num < ord('A'):
                    num += 26
            elif symbol.islower():
                if num > ord('z'):
                    num -= 26
                elif num < ord('a'):
                    num += 26

            translated += chr(num)
        else:
            translated += symbol
    return translated
Пример #14
0
	def read(self, type, oaddr):
		"""Decode result from read1 or read2 commands.

		type: "1" or "2"
		oaddr: probe address

		Return:
		float: if result is valid.
		"underread" or "overread": if result is out of range.

		raises exception if device type is unknown by the driver.
		"""

		info = self.probes[oaddr-1]
		command = "read%s" % type
		result = self.execute(command, oaddr)

		response = ord(result[2])
		if response == 33:
			status = ord(result[3])
			if status == 18:
				return "underread"
			if status == 19:
				return "overread"

		value = struct.unpack(self.reply_format[command], result)[1]

		if info["moduletype"] == "DP":
			return float(value)/16384 * info["stroke"]

		raise NotImplementedError("Reading calculation not implemented for this module.")
Пример #15
0
def caeser_cypher(key, action, data):

    result_str = ""
    if action == 'decode':
        key = -key

    for sym in data:
        if sym.isalpha():
            num = ord(sym)
            num += key
            if sym.isupper():
                if num > ord('Z'):
                    num -= 26
                elif num < ord('A'):
                    num += 26
            else:
                if num > ord('z'):
                    num -= 26
                elif num < ord('a'):
                    num += 26

            result_str += chr(num)
        else:
            result_str += sym
    logging.info("OUTPUT: {}".format(result_str))
Пример #16
0
def test_random_addition_and_slicing():
    seed = random.randrange(10000)
    print seed
    random.seed(seed)
    st = "abc"
    curr = LiteralStringNode(st)
    last = None
    all = []
    for i in range(1000):
        a = (chr(random.randrange(ord('a'), ord('z') + 1)) *
                random.randrange(500))
        last = curr
        all.append(curr)
        c = random.choice([0, 1, 2])
        if c == 0:
            curr = curr + LiteralStringNode(a)
            st = st + a
        elif c == 1:
            curr = LiteralStringNode(a) + curr
            st = a + st
        else:
            if len(st) < 10:
                continue
            # get a significant portion of the string
            #import pdb; pdb.set_trace()
            start = random.randrange(len(st) // 3)
            stop = random.randrange(len(st) // 3 * 2, len(st))
            curr = getslice_one(curr, start, stop)
            st = st[start: stop]
        assert curr.flatten_string() == st
    curr = curr.rebalance()
    assert curr.flatten_string() == st
Пример #17
0
def html_escape(text):
  escaped_chars = ""
  for c in text:
    if (ord(c) < 32) or (ord(c) > 126):
      c = '&{};'.format(htmlentitydefs.codepoint2name[ord(c)])
    escaped_chars = escaped_chars + c
  return escaped_chars
Пример #18
0
def test_prompt_y_or_n(terminal, stdscr):

    stdscr.getch.side_effect = [ord('y'), ord('N'), terminal.ESCAPE, ord('a')]
    attr = Color.CYAN | curses.A_BOLD
    text = 'hi'.encode('ascii')

    # Press 'y'
    assert terminal.prompt_y_or_n('hi')
    stdscr.subwin.addstr.assert_called_with(0, 0, text, attr)
    assert not curses.flash.called

    # Press 'N'
    assert not terminal.prompt_y_or_n('hi')
    stdscr.subwin.addstr.assert_called_with(0, 0, text, attr)
    assert not curses.flash.called

    # Press Esc
    assert not terminal.prompt_y_or_n('hi')
    stdscr.subwin.addstr.assert_called_with(0, 0, text, attr)
    assert not curses.flash.called

    # Press an invalid key
    assert not terminal.prompt_y_or_n('hi')
    stdscr.subwin.addstr.assert_called_with(0, 0, text, attr)
    assert curses.flash.called
Пример #19
0
def checksum(source_string):
    """
    I'm not too confident that this is right but testing seems
    to suggest that it gives the same answers as in_cksum in ping.c
    """
    sum = 0
    countTo = (len(source_string)/2)*2
    count = 0
    while count<countTo:
        thisVal = ord(source_string[count + 1])*256 + ord(source_string[count])
        sum = sum + thisVal
        sum = sum & 0xffffffff # Necessary?
        count = count + 2
 
    if countTo<len(source_string):
        sum = sum + ord(source_string[len(source_string) - 1])
        sum = sum & 0xffffffff # Necessary?
 
    sum = (sum >> 16)  +  (sum & 0xffff)
    sum = sum + (sum >> 16)
    answer = ~sum
    answer = answer & 0xffff
 
    # Swap bytes. Bugger me if I know why.
    answer = answer >> 8 | (answer << 8 & 0xff00)
 
    return answer
Пример #20
0
 def __init__(self, data, sensors, model):
     """
     Initializes packet data. Sets the global battery value.
     Updates each sensor with current sensor value from the packet data.
     """
     global g_battery
     self.raw_data = data
     self.counter = ord(data[0])
     self.battery = g_battery
     if self.counter > 127:
         self.battery = self.counter
         g_battery = battery_values[str(self.battery)]
         self.counter = 128
     self.sync = self.counter == 0xe9
     self.gyro_x = ord(data[29]) - 106
     self.gyro_y = ord(data[30]) - 105
     sensors['X']['value'] = self.gyro_x
     sensors['Y']['value'] = self.gyro_y
     for name, bits in sensor_bits.items():
         #Get Level for sensors subtract 8192 to get signed value
         value = get_level(self.raw_data, bits) - 8192
         setattr(self, name, (value,))
         sensors[name]['value'] = value
     self.old_model = model
     self.handle_quality(sensors)
     self.sensors = sensors
Пример #21
0
    def test_findall(self):
        list_len = 10
        range_label = 'A1:A%s' % list_len
        cell_list = self.sheet.range(range_label)
        value = gen_value()

        for c in cell_list:
            c.value = value
        self.sheet.update_cells(cell_list)

        result_list = self.sheet.findall(value)

        self.assertEqual(list_len, len(result_list))

        for c in result_list:
            self.assertEqual(c.value, value)

        cell_list = self.sheet.range(range_label)

        value = gen_value()
        for c in cell_list:
            char = chr(random.randrange(ord('a'), ord('z')))
            c.value = "%s%s_%s%s" % (c.value, char, char.upper(), value)

        self.sheet.update_cells(cell_list)

        o_O_re = re.compile('[a-z]_[A-Z]%s' % value)

        result_list = self.sheet.findall(o_O_re)

        self.assertEqual(list_len, len(result_list))
Пример #22
0
    def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
        """
        Render the text
        """
        if __debug__: verbose.report('RendererAgg.draw_text', 'debug-annoying')

        if ismath:
            return self.draw_mathtext(gc, x, y, s, prop, angle)

        flags = get_hinting_flag()
        font = self._get_agg_font(prop)
        if font is None: return None
        if len(s) == 1 and ord(s) > 127:
            font.load_char(ord(s), flags=flags)
        else:
            # We pass '0' for angle here, since it will be rotated (in raster
            # space) in the following call to draw_text_image).
            font.set_text(s, 0, flags=flags)
        font.draw_glyphs_to_bitmap(antialiased=rcParams['text.antialiased'])
        d = font.get_descent() / 64.0
        # The descent needs to be adjusted for the angle
        xo, yo = font.get_bitmap_offset()
        xo /= 64.0
        yo /= 64.0
        xd = -d * np.sin(np.deg2rad(angle))
        yd = d * np.cos(np.deg2rad(angle))

        #print x, y, int(x), int(y), s
        self._renderer.draw_text_image(
            font, np.round(x - xd + xo), np.round(y + yd + yo) + 1, angle, gc)
Пример #23
0
Файл: IRC.py Проект: Peping/Lal
    def parse_line(self, nick, hostname, remainder):
        (argsstr, message) = remainder.split(" :",1) if " :" in remainder else (remainder.strip(),"")
        args = argsstr.split(" ")
        command = args[0]
        args = args[1:]

        if command=="PRIVMSG":
            if ord(message[0])==1 and ord(message[-1])==1:
                stripped = message[1:-1]
                first_space = stripped.find(" ")
                ctcp_command = stripped[:first_space] if first_space!=-1 else stripped
                ctcp_message = stripped[first_space+1:] if first_space!=-1 else ""
                self.raise_event("ctcp", is_request=True, origin=nick, message=ctcp_message, command=ctcp_command)
            elif len(args)==1:
                if args[0] == self.nickname:
                    self.raise_event("query",origin=nick, message=message)
                else: self.raise_event("channel message", origin=nick, channel=args[0], message=message)
        elif command=="NOTICE":
            if ord(message[0])==1 and ord(message[-1])==1:
                stripped = message[1:-1]
                first_space = stripped.find(" ")
                ctcp_command = stripped[:first_space] if first_space!=-1 else stripped
                ctcp_message = stripped[first_space+1:] if first_space!=-1 else ""
                self.raise_event("ctcp", is_request=False, origin=nick, message=ctcp_message, command=ctcp_command)
            elif len(args)==1:
                if args[0] == self.nickname:
                    self.raise_event("notice",origin=nick, message=message)
                else: self.raise_event("channel notice", origin=nick, channel=args[0], message=message)
        elif command=="JOIN":
            self.raise_event("joined", nick=nick, channel=message)
        elif command=="PART":
            self.raise_event("left", nick=nick, channel=message)
        elif command=="NICK":
            self.raise_event("nick", nick=nick, new_nick=message)
Пример #24
0
    def is_animated_gif(self, data):
        if data[:6] not in [b"GIF87a", b"GIF89a"]:
            return False
        i = 10  # skip header
        frames = 0

        def skip_color_table(i, flags):
            if flags & 0x80:
                i += 3 << ((flags & 7) + 1)
            return i

        flags = ord(data[i])
        i = skip_color_table(i + 3, flags)
        while frames < 2:
            block = data[i]
            i += 1
            if block == b'\x3B':
                break
            if block == b'\x21':
                i += 1
            elif block == b'\x2C':
                frames += 1
                i += 8
                i = skip_color_table(i + 1, ord(data[i]))
                i += 1
            else:
                return False
            while True:
                j = ord(data[i])
                i += 1
                if not j:
                    break
                i += j
        return frames > 1
Пример #25
0
    def __init__(self, my_map, my_total):
        self.STUDENT = ord('S')
        self.GROCERY = ord('G')
        self.PIZZA = ord('P')
        self.WALL = ord('W')

        self.FORWARD = 0
        self.RIGHT = 1
        self.LEFT = 2
        self.STAY = 3
        self.NORMAL = 5
        
        self.NORTH = 0
        self.EAST = 1
        self.SOUTH = 2
        self.WEST = 3

        self.row = 6
        self.col = 2
        self.time = 0
        self.alpha = 1
        self.total = float(my_total)
        self.map = my_map

        self.groceries = True
        self.pizzas = False

        self.lookup = np.array([
            [[-1, 0], [0, 1], [0, -1], [0, 0]],
            [[0, 1], [1, 0], [-1, 0], [0, 0]],
            [[1, 0], [0, -1], [0, 1], [0, 0]],
            [[0, -1], [-1, 0], [1, 0], [0, 0]]
        ])
Пример #26
0
def check_update (neighbor, raw):
	from exabgp.logger import Logger

	logger = Logger()
	logger._parser = True
	logger.parser('\ndecoding routes in configuration')

	n = neighbor[neighbor.keys()[0]]
	p = Peer(n,None)

	path = {}
	for f in known_families():
		if n.add_path:
			path[f] = n.add_path

	capa = Capabilities().new(n,False)
	capa[Capability.CODE.ADD_PATH] = path
	capa[Capability.CODE.MULTIPROTOCOL] = n.families()

	routerid_1 = str(n.router_id)
	routerid_2 = '.'.join(str((int(_)+1) % 250) for _ in str(n.router_id).split('.',-1))

	o1 = Open(4,n.local_as,routerid_1,capa,180)
	o2 = Open(4,n.peer_as,routerid_2,capa,180)
	negotiated = Negotiated(n)
	negotiated.sent(o1)
	negotiated.received(o2)
	# grouped = False

	while raw:
		if raw.startswith('\xff'*16):
			kind = ord(raw[18])
			size = (ord(raw[16]) << 16) + (ord(raw[17]))

			injected,raw = raw[19:size],raw[size:]

			if kind == 2:
				logger.parser('the message is an update')
				decoding = 'update'
			else:
				logger.parser('the message is not an update (%d) - aborting' % kind)
				return False
		else:
			logger.parser('header missing, assuming this message is ONE update')
			decoding = 'update'
			injected,raw = raw,''

		try:
			# This does not take the BGP header - let's assume we will not break that :)
			update = Update.unpack_message(injected,negotiated)
		except KeyboardInterrupt:
			raise
		except Notify,exc:
			logger.parser('could not parse the message')
			logger.parser(str(exc))
			return False
		except Exception,exc:
			logger.parser('could not parse the message')
			logger.parser(str(exc))
			return False
Пример #27
0
def _check_end_after_start(start, end) -> None:
    reverse_start = start[::-1]
    reverse_end = end[::-1]
    e = sum((26 ** i) * ord(c) for i, c in enumerate(reverse_end))
    s = sum((26 ** i) * ord(c) for i, c in enumerate(reverse_start))
    if s > e:
        raise ValueError("start value {0} before end value {1}".format(start, end))
Пример #28
0
def main():
    files = glob.glob("./scans/*.jpg")
    files += glob.glob("./scans/*.jpeg")
    for f in files:
        reset_stats()
        print "Processing: " + f.split("/")[len(f.split("/")) - 1]

        schedule = Schedule()
        schedule.load_data()
        if schedule.get_has_schedule():
            scan_image(f, schedule)

            print "Sheet ok? ",
            while True:
                cv2.imshow("image", cv2.resize(img, (446, 578)))
                cv2.moveWindow("image", 0, 0)
                # user_in = raw_input()
                key = cv2.waitKey(-1)
                if key == ord("y"):
                    print "Sheet ok... Dumping data"
                    dump_stats()
                    os.remove(f)
                    break
                elif key == ord("n"):
                    print "Marking to redo"
                    #os.rename(f, "./scans/redo/" + f.split("/")[len(f.split("/")) - 1])
                    break
                elif key == ord("q"):
                    exit(0)
                else:
                    continue
            cv2.destroyAllWindows()
        else:
            print "Unable to load schedule... Aborting"
Пример #29
0
def get_coord(character):
    width = 5
    assert 'a' <= character <= 'z', "invalid character"
    ref = ord('a')
    x = (ord(character) - ref) % width
    y = (ord(character) - ref) / width
    return (x, y)
Пример #30
0
def get_nsa_class (ipInfo=None, ip=None, conn=None, long_lat=None):
    
    if long_lat:
        (longitude, latitude) = long_lat

    else:
        if not ipInfo:
            ipInfo = get_ip_addr_info (ip, conn)

        longitude = ipInfo['long']
        latitude = ipInfo['lat']

    if not conn:
        conn = ixmaps.DBConnect.getConnection()

    all_chotels = ixmaps.CHotels(conn)
    chotels_in_city_list = all_chotels.all_within (longitude, latitude, 
                                                   MAX_NSA_DIST)
    chotels_in_city = ixmaps.CHotels (chotels=chotels_in_city_list)
    nsa_posts_in_city_list = chotels_in_city.get_type('NSA')
    

    # chotel = all_chotels.nsa_in_city (float(longitude), float(latitude),
                                      # (MAX_CHOTEL_DIST*20))

    if not nsa_posts_in_city_list:
        nsa_type = None

    else:
        nsa_type = 'Z'
        for nsa in nsa_posts_in_city_list:
            if ( ord(nsa['nsa']) < ord(nsa_type) ):
                nsa_type = nsa['nsa']

    return nsa_type
Пример #31
0
def process_data(d):
    r = struct.unpack('<HHxxBB', d[2:])
    pm25 = r[0] / 10.0
    pm10 = r[1] / 10.0
    checksum = sum(ord(v) for v in d[2:8]) % 256
    return [pm25, pm10]
Пример #32
0
while (True):
    ret, frame = cap.read()
    cv2.imshow('frame', frame)
    output = frame.copy()
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    lower_green = np.array([65, 60, 60])
    upper_green = np.array([80, 255, 255])
    mask1 = cv2.inRange(hsv, lower_green, upper_green)
    lower_green = (29, 86, 6)
    upper_green = (64, 255, 255)
    mask2 = cv2.inRange(hsv, lower_green, upper_green)
    mask = mask1 + mask2
    res = cv2.bitwise_and(frame, frame, mask=mask)
    gray = cv2.cvtColor(res, cv2.COLOR_BGR2GRAY)
    cv2.imshow('res', res)
    circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1.2, 10)
    if circles is not None:
        circles = np.round(circles[0, :]).astype("int")
        ser.write(1)
        print(1)
        for (x, y, r) in circles:
            cv2.circle(output, (x, y), r, (0, 255, 0), 4)
        cv2.imshow("output", output)
    else:
        ser.write(0)
        print(0)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()
Пример #33
0
                p1 = (int(image_points[0][0]), int(image_points[0][1]))
                p2 = (int(nose_end_point2D[0][0][0]),
                      int(nose_end_point2D[0][0][1]))
                cv2.line(frame, p1, p2, (255, 0, 0), 2)

        # Get image dimensions
        #height, width = image.shape[:2]

        # Output frame to file
        out.write(frame)
        # Display image to screen
        cv2.imshow('Output Image', frame)
        # Wait for key press 0
        cv2.waitKey(1)

        # Write the frame into the file 'output.avi'
        #out.write(res)
        i += 1

        # Press Q on keyboard to  exit
        # If live camera replace waitKey(25) to waitKey(1)
        if cv2.waitKey(25) & 0xFF == ord('q'):
            break
    # Break the loop
    else:
        break

# Remove all windows when finished
out.release()
cv2.destroyAllWindows()
Пример #34
0
import os
src = 'D:\git\crawler\zigbang\\test\class\\'
dest = 'images\\'
def random_pick(path):
  return os.listdir(path)[np.random.randint(0,len(os.listdir(path)))]
img = cv2.imread(os.path.join(src,random_pick(src)), cv2.IMREAD_COLOR)

img_masked = img.copy()
mask = np.zeros(img.shape[:2], np.uint8)

sketcher = Sketcher('image', [img_masked, mask], lambda : ((255, 255, 255), 255))
chunker = ImageChunker(512, 512, 30)

while True:
  key = cv2.waitKey()
  if key == ord('s'): #save
    sketcher.save_files(dest)
  if key == ord('c'):
    new_img = cv2.imread(os.path.join(src, random_pick(src)), cv2.IMREAD_COLOR)
    new_mask = np.zeros(new_img.shape[:2],np.uint8)
    sketcher.dests[0] = new_img
    sketcher.dests[1] = new_mask
    sketcher.show()
  if key == ord('q'): # quit
    break
  if key == ord('r'): # reset
    print('reset')
    img_masked[:] = img
    mask[:] = 0
    sketcher.show()
  if key == 32: # hit spacebar to run inpainting
c = open("fibcrypted.txt").read()
cm = [ord(x) for x in c]

while not c.startswith("flag{"):
    newChr = ord(c[0])-ord(c[1])
    if newChr<0:
        newChr+=128
    c+=chr(newChr)
    c=c[1:]

print c
Пример #36
0
def cell_tuple2str(coords):
    col = chr(ord('A') + coords[0] - 1)
    row = str(coords[1])
    return col + row
Пример #37
0
def cell_str2tuple(string):
    col = ord(string[0]) - ord('A') + 1
    row = int(string[1])
    return (col, row)
Пример #38
0
def main():

    WINDOW = True
    NETWORKING = False
    CONFIGURE = True

    NetworkTables.initialize(server="10.26.43.2")

    if NETWORKING:
        print("connecting to network");
        # Wait for networktables to connect 
        while not NetworkTables.isConnected():
            print("waiting to connect...")
            time.sleep(0.5)
            pass

        print("connected")
        visionTable = NetworkTables.getTable("vision")

    cap = cv2.VideoCapture(2)

    if CONFIGURE:
        print("configuring camera")
        cap.set(cv2.CAP_PROP_FPS, 30)
        cap.set(cv2.CAP_PROP_AUTO_EXPOSURE, 1)
        cap.set(cv2.CAP_PROP_EXPOSURE, 2)
        print("camera configuration complete")

    # get dimensions of video feed
    xsize = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
    ysize = cap.get(cv2.CAP_PROP_FRAME_HEIGHT) 


    while True:
        frame = cap.read()[1]
        hsv_thresh = cv2.inRange(cv2.cvtColor(frame, cv2.COLOR_BGR2HSV), 
                                 (113, 89, 0), 
                                 (123, 255, 80))

        closed = erode(hsv_thresh, (5,5), 2)
        closed = dilate(closed, (5,5), 2)

        if opencvVersion() == 3:
            _, contours, _ = cv2.findContours(closed, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE);
        else:
            contours, _ = cv2.findContours(closed, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

        rect1 = None
        rect2 = None
        contours.sort(key = lambda x: cv2.contourArea(x), reverse=True)


        # decide on right rect and left rect (it's the largest one with a slope in the right direction)
        for contour in contours: 
            rect = getRect(contour)
            slope = getRectangleTiltSlope(rect)
            cv2.drawContours(frame,[rect],0,(255,0,0),2)
            if slope > 0 and cv2.contourArea(rect) > 0:
                cv2.drawContours(frame,[rect],0,(0,0,255),2)
                rect1 = rect
                break

        # Draw to screen
        for contour in contours:
            rect = getRect(contour)
            slope = getRectangleTiltSlope(rect)
            cv2.drawContours(frame,[rect],0,(255,0,0),2)
            if slope < -0 and cv2.contourArea(rect) > 0:
                cv2.drawContours(frame,[rect],0,(0,0,255),2)
                rect2 = rect
                break


        valid = False
        centroid_left_x = 0.0
        centroid_left_y = 0.0
        centroid_right_x = 0.0
        centroid_right_y = 0.0
        centroid_left_area = 0.0
        centroid_right_area = 0.0

        # If we have 2 rectangles and they're arranged in the right way
        if rect1 is not None and rect2 is not None and getCentroid(rect1)[0] < getCentroid(rect2)[0]:
            valid = True
            centroid1 = getCentroid(rect1)
            centroid2 = getCentroid(rect2)
            relative1 = getRelative(centroid1[0], centroid1[1], xsize, ysize)
            relative2 = getRelative(centroid2[0], centroid2[1], xsize, ysize)
            centroid_left_x = relative1[0]
            centroid_left_y = relative1[1]
            centroid_right_x = relative2[0]
            centroid_right_y = relative2[1]
        else:
            valid = False

        
        # print("valid: ", valid, " l: ", centroid_left_x, " r: ", centroid_right_x)


        if NETWORKING:
            # Send the data to the computer
            visionTable.putNumber("centroid-left-x", centroid_left_x)
            visionTable.putNumber("centroid-left-y", centroid_left_y)
            visionTable.putNumber("centroid-right-x", centroid_right_x)
            visionTable.putNumber("centroid-right-y", centroid_right_y)
            visionTable.putBoolean("valid", valid)

        if WINDOW:
            cv2.imshow("raw_image", frame)
            cv2.imshow("processed_image", closed)
            if cv2.waitKey() == ord('q'):
                break
        


    # When everything done, release the capture
    cap.release()
Пример #39
0
            RF = RFs[y,x]
            vmin = min(vmin,RF.min())
            vmax = max(vmax,RF.max())

    for i in range(4):
        for j in range(4):
            index = i*4+j
            y,x = indices[index]

            RF = RFs[y,x]

#            s0,s1 = np.unravel_index(np.argmax(RF),RF.shape)
#            RF = np.roll(RF,12-s0,axis=0)
#            RF = np.roll(RF,12-s1,axis=1)

            vmin, vmax =  RF.min(), RF.max()

            plt.subplot2grid((4,4),(i,j),rowspan=1,colspan=1)
            plt.imshow( RF, interpolation='nearest', cmap=plt.cm.gray_r, origin='lower',
                        vmin=vmin, vmax=vmax)

            plt.axis([0,RFs.shape[2]-1,0,RFs.shape[2]-1])
            plt.xticks([]), plt.yticks([])
            plt.text(1,1,'%c' % (ord('A')+index), weight='bold', fontsize=20, color='w',
                  path_effects=[PathEffects.withStroke(linewidth=1.5, foreground="k", alpha=.5)])


    print vmin,vmax
    plt.savefig('matrix-rfs.pdf', dpi=100 )
    plt.show()
Пример #40
0
#-*- coding:utf-8 -*-

from random import randrange, choice  # generate and place new tile
from collections import defaultdict

letter_codes = [ord(ch) for ch in 'WASDRQwasdrq']  #所有的有效输入都可以转换为"上,下,左,右,游戏重置,退出"这六种行为
actions = ['Up', 'Left', 'Down', 'Right', 'Restart', 'Exit']  #有效输入键是最常见的 W(上),A(左),S(下),D(右),R(重置),Q(退出),这里要考虑到大写键开启的情况,获得有效键值列表:
actions_dict = dict(zip(letter_codes, actions * 2))  #将输入与行为进行关联


def get_user_action(keyboard):  
    #阻塞+循环直到获得用户有效输入才返回对应行为:  
    char = "N"
    while char not in actions_dict:    
        char = keyboard.getch()
    return actions_dict[char]

def transpose(field):
    #矩阵转置
    return [list(row) for row in zip(*field)]

def invert(field):
    #矩阵逆转(不是逆矩阵)
    return [row[::-1] for row in field]


class GameField(object):
    #创建初始化盘的参数
    def __init__(self, height=4, width=4, win=2048):
        self.height = height          #高
        self.width = width            #宽
Пример #41
0
cv2.imshow('Test',img)

        # OpenCV Logo
# Create another black image
img2 = np.ones((512,512,3), np.uint8)
# Draw the red circle
img2 = cv2.circle(img2,(256,130),55,(0,0,255),42,lineType)
# Draw the green circle
img2 = cv2.circle(img2,(159,291),55,(0,255,0),42,lineType)
# Cut through the circles above
trit1 = np.array([[256,130],[159,291],[348,291]], np.int32)
trit1 = trit1.reshape((-1,1,2))
img2 = cv2.fillPoly(img2,[trit1],0,lineType)
# Draw the blue circle
img2 = cv2.circle(img2,(348,291),55,(255,0,0),42,lineType)
# Cut through the circle above
trit2 = np.array([[348,291],[297,211],[399,211]], np.int32)
trit2 = trit2.reshape((-1,1,2))
img2 = cv2.fillPoly(img2,[trit2],0,lineType)
# Write 'OpenCV' at the bottom
cv2.putText(img2,'OpenCV',(20,475), font, 4,(255,255,255),12,lineType)

cv2.imshow('OpenCV Logo',img2)

k = cv2.waitKey(0) & 0xFF

if k == 27:
    cv2.destroyAllWindows()
elif k == ord('s'):
    cv2.imwrite('OpenCV_Logo.png',img2)
    cv2.destroyAllWindows()
Пример #42
0
Файл: m.py Проект: dthinkcs/ps
def caesarCipherEncryptor(string, key):
    # Write your code here.
    strn = ""
    for i in range(len(string)):
        strn += chr((ord(string[i]) - ord('a') + key) % 26 + ord('a'))
    return strn
Пример #43
0
def xor(x):
    return ''.join(chr(ord(i)^10) for i in x)
Пример #44
0
def read_byte(ea):
    byte = read_bytes_slowly(ea, ea + 1)
    byte = ord(byte)
    return byte
Пример #45
0
	def __str__(self):
		s = '[%02x_%02x_%02x_%x] '%(ord(self.data[0]),ord(self.data[1]),ord(self.data[2]),ord(self.data[3])>>4)
		return s + OvcRecord.__str__(self)
Пример #46
0
import cv2
# initalize the cam
cap = cv2.VideoCapture(0)
# initialize the cv2 QRCode detector
detector = cv2.QRCodeDetector()
while True:
    _, img = cap.read()
    # detect and decode
    data, bbox, _ = detector.detectAndDecode(img)
    # check if there is a QRCode in the image
    if bbox is not None:
        # display the image with lines
        for i in range(len(bbox)):
            # draw all lines
            cv2.line(img,
                     tuple(bbox[i][0]),
                     tuple(bbox[(i + 1) % len(bbox)][0]),
                     color=(255, 0, 0),
                     thickness=2)
        if data:
            print("[+] QR Code detected, data:", data)
    # display the result
    cv2.imshow("img", img)
    if cv2.waitKey(1) == ord("q"):
        break
cap.release()
cv2.destroyAllWindows()
#Write a program to accept an alphanumeric string from the user.
#Now extract only digits from the given input and add it to the list.
#Finally print the list.
#Make sure your list contains numeric representation of digits
string=input("enter an alphanumeric string\t:")
num_list=list()
for i in string:
    if 48<=ord(i)<=57:
        num_list.append(int(i))
print("numbers present in above string =",num_list)
Пример #48
0
    #ax4.bar(index, optical_direction, color='r', label='degree')
    plt.draw()
    
    # updare cx_neurons
    velocity = np.array([sl, sr])
    tl2, cl1, tb1, tn1, tn2, memory, cpu4, cpu1, motor = update_cells(
            heading=heading_list[frame_num]/180.0*np.pi, velocity=velocity, tb1=tb1, memory=memory, cx=cx)
    angle, distance = cx.decode_cpu4(cpu4)
    angle_list[frame_num] = angle/np.pi*180.0
    distance_list[frame_num] = distance

    # show frames
    cv2.imshow('vedio', cv2.resize(draw_flow(next, flow), (0,0), fx=3.0, fy=3.0))
    #print('Frame number: ', frame_num)
    ch = cv2.waitKey(5) & 0xFF 
    if ch == ord('q'):
        break
    elif ch == ord(' '):
        while True:
            ch = cv2.waitKey(5) & 0xFF
            if ch == ord(' ') or ch == ord('q'):
                break
            time.sleep(0.2)
    prvs = next
    start_time = time.time()


ax1.clear()
ax2.clear()
ax3.clear()
ax4.clear()
            # print "Id: ", Id

            if(Id == userId):
                result = 1
                break
            else:
                result = 0
            # print("step: ", i ," result: ", result)
            i += 1
            cv2.waitKey(300)
        
        # cv2.imshow("Camera", img)

        if(i > 10):
            break
        if (cv2.waitKey(1) == ord('q')):
            break
    if (result == 1):
        break;

cam.release()
cv2.destroyAllWindows()

if (result == 1):
    result = str(result)
    result = "yes"
else:
    result = str(result)
    result = "no"

# result = json.dumps(result)
Пример #50
0
def process_version(d):
    r = struct.unpack('<BBBHBB', d[3:])
    checksum = sum(ord(v) for v in d[2:8]) % 256
    print("Y: {}, M: {}, D: {}, ID: {}, CRC={}".format(
        r[0], r[1], r[2], hex(r[3]), "OK" if
        (checksum == r[4] and r[5] == 0xab) else "NOK"))
Пример #51
0
 def ispunct(s):
     return s is not None and ord(s[0]) > 32 and not s[0].isalnum()
Пример #52
0
a = input()
b = input()
cnt = [0] * 26
offset = ord('a')
for char in a:
	cnt[ord(char) - offset] += 1
print(cnt)
for char in b:
	cnt[ord(char) - offset] -= 1
	print(cnt)
total = 0
print(cnt)
for value in cnt:
	total += abs(value)
print(total)
Пример #53
0
def unicode_to_ks0066u(string):
    if sys.hexversion < 0x03000000:
        byte = lambda x: chr(x)
        ks0066u = ''

        if type(string) != types.UnicodeType:
            code_points = unicode(string, 'UTF-8')
        else:
            code_points = string
    else:
        byte = lambda x: bytes([x])
        ks0066u = bytes()
        code_points = string

    for code_point in code_points:
        code_point = ord(code_point)

        # ASCII subset from JIS X 0201
        if code_point >= 0x0020 and code_point <= 0x007e:
            # The LCD charset doesn't include '\' and '~', use similar characters instead
            mapping = {
                0x005c : byte(0xa4), # REVERSE SOLIDUS maps to HALFWIDTH IDEOGRAPHIC COMMA
                0x007e : byte(0x2d)  # TILDE maps to HYPHEN-MINUS
            }

            try:
                c = mapping[code_point]
            except KeyError:
                c = byte(code_point)
        # Katakana subset from JIS X 0201
        elif code_point >= 0xff61 and code_point <= 0xff9f:
            c = byte(code_point - 0xfec0)
        # Special characters
        else:
            mapping = {
                0x00a5 : byte(0x5c), # YEN SIGN
                0x2192 : byte(0x7e), # RIGHTWARDS ARROW
                0x2190 : byte(0x7f), # LEFTWARDS ARROW
                0x00b0 : byte(0xdf), # DEGREE SIGN maps to KATAKANA SEMI-VOICED SOUND MARK
                0x03b1 : byte(0xe0), # GREEK SMALL LETTER ALPHA
                0x00c4 : byte(0xe1), # LATIN CAPITAL LETTER A WITH DIAERESIS
                0x00e4 : byte(0xe1), # LATIN SMALL LETTER A WITH DIAERESIS
                0x00df : byte(0xe2), # LATIN SMALL LETTER SHARP S
                0x03b5 : byte(0xe3), # GREEK SMALL LETTER EPSILON
                0x00b5 : byte(0xe4), # MICRO SIGN
                0x03bc : byte(0xe4), # GREEK SMALL LETTER MU
                0x03c2 : byte(0xe5), # GREEK SMALL LETTER FINAL SIGMA
                0x03c1 : byte(0xe6), # GREEK SMALL LETTER RHO
                0x221a : byte(0xe8), # SQUARE ROOT
                0x00b9 : byte(0xe9), # SUPERSCRIPT ONE maps to SUPERSCRIPT (minus) ONE
                0x00a4 : byte(0xeb), # CURRENCY SIGN
                0x00a2 : byte(0xec), # CENT SIGN
                0x2c60 : byte(0xed), # LATIN CAPITAL LETTER L WITH DOUBLE BAR
                0x00f1 : byte(0xee), # LATIN SMALL LETTER N WITH TILDE
                0x00d6 : byte(0xef), # LATIN CAPITAL LETTER O WITH DIAERESIS
                0x00f6 : byte(0xef), # LATIN SMALL LETTER O WITH DIAERESIS
                0x03f4 : byte(0xf2), # GREEK CAPITAL THETA SYMBOL
                0x221e : byte(0xf3), # INFINITY
                0x03a9 : byte(0xf4), # GREEK CAPITAL LETTER OMEGA
                0x00dc : byte(0xf5), # LATIN CAPITAL LETTER U WITH DIAERESIS
                0x00fc : byte(0xf5), # LATIN SMALL LETTER U WITH DIAERESIS
                0x03a3 : byte(0xf6), # GREEK CAPITAL LETTER SIGMA
                0x03c0 : byte(0xf7), # GREEK SMALL LETTER PI
                0x0304 : byte(0xf8), # COMBINING MACRON
                0x00f7 : byte(0xfd), # DIVISION SIGN
                0x25a0 : byte(0xff)  # BLACK SQUARE
            }

            try:
                c = mapping[code_point]
            except KeyError:
                c = byte(0xff) # BLACK SQUARE

        # Special handling for 'x' followed by COMBINING MACRON
        if c == byte(0xf8):
            if len(ks0066u) == 0 or not ks0066u.endswith(byte(0x78)):
                c = byte(0xff) # BLACK SQUARE

            if len(ks0066u) > 0:
                ks0066u = ks0066u[:-1]

        ks0066u += c

    return ks0066u
Пример #54
0
# For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.
# What is the total of all the name scores in the file?

from datetime import datetime

start = datetime.now()

txt = open('euler22.txt').read()

s = []

x = 0

while x < len(txt):
    c = ''
    while ord(txt[x]) in range(65, 91):
        c += txt[x]
        x += 1
    if c <> '':
        s.append(c)
    x += 1

s = sorted(s)

base = 0

for x in xrange(0, len(s), 1):
    temp = 0
    for y in xrange(0, len(s[x]), 1):
        temp += (ord(s[x][y]) - 64)
    base += temp * (x + 1)
    return copy_line


for line in read:
    lines.append(get_valid_lines(line))

dic = {}

for line in lines:
    for letter in line:
        if not letter in dic:
            dic[letter] = 0
        dic[letter] += 1

for (key, value) in sorted(dic.items()):
    print(key, ord(key), '---', value)

from bengali_stemmer import BengaliStemmer
bs = BengaliStemmer()
bs.stem_word(word='হেরে')
#টানা তিন ম্যাচে হেরে হোয়াইটওয়াশ
s = {}
cnt = 0
for line in lines:
    for one in line.splitlines():
        cnt += 1
        for two in one.split():
            word = bs.stem_word(two)
            if not word in s:
                s[word] = 0
            s[word] += 1
Пример #56
0
def show_cam(camera=0, bw=False, mirrorlr=False, mirrorud=False, hsv=False, detect_region=False):
    cam = cv2.VideoCapture(camera)
    try:
        while True:
            img_available, img = cam.read()


            if img_available==True:
                # convert the image to grayscale
                img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
                img = cv2.normalize(img,img,0,255,cv2.NORM_MINMAX)
                img = cv2.addWeighted( img, 1.5, np.zeros(img.shape, img.dtype), 0, 0)

                
                if detect_region:
                    box = detect_qr(img)
                    # draw a bounding box arounded the detected QR code 
                    # cv2.drawContours(img, [box], -1, (0, 255, 0), 3)

                    # Set area outside region of interest to white
                    mask = np.zeros_like(img) # Create mask where white is what we want, black otherwise
                    for bx in box:
                        cv2.fillConvexPoly(mask, np.array(bx), 255)
                    out = 255*np.ones_like(img)
                    out[mask == 255] = img[mask == 255]
                    img = out


                if hsv:
                    img = cv2.normalize(img,img,0,255,cv2.NORM_MINMAX)
                    img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)


                    # define range of bw color in HSV
                    sat_limit = 40
                    lower_bw = np.array([0,0,0])
                    upper_bw = np.array([255,sat_limit,255])

                    # Threshold the HSV image to get only white colors
                    mask = cv2.inRange(img_hsv, lower_bw, upper_bw)
                    # Bitwise-AND mask and original image
                    img = cv2.bitwise_and(img,img, mask= mask)
                
                # Cast to BW image
                if bw:
                    # Up contrast
                    img = cv2.addWeighted(img, 3, np.zeros(img.shape, img.dtype), 0, 0)

                    # blur noise
                    img = cv2.bilateralFilter(img,5,75,75)

                    
                    # blur = cv2.GaussianBlur(img,(5,5),0)
                    # _, img = cv2.threshold(img,0,255,cv2.THRESH_OTSU)
                    _, img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
                    # _, img = cv2.threshold(img, img.mean()/2, 255, cv2.THRESH_TOZERO)
                    # _, img = cv2.threshold(img, 200, , cv2.THRESH_TOZERO_INV)



                decoded = decode(img)
                if len(decoded) > 0:
                    print(decoded)

                # Flip image if necessary
                if mirrorlr:
                    img = cv2.flip(img,1)
                if mirrorud:
                    img = cv2.flip(img,0)

                cv2.imshow('my cam', img)


            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
    finally:
        cam.release()
        cv2.destroyAllWindows()
    frame = imutils.resize(frame, width=400)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # detect faces in the grayscale frame
    rects = detector(gray, 0)

    # loop over the face detections
    for rect in rects:
        # determine the facial landmarks for the face region, then
        # convert the facial landmark (x, y)-coordinates to a NumPy
        # array
        shape = predictor(gray, rect)
        shape = face_utils.shape_to_np(shape)

        # loop over the (x, y)-coordinates for the facial landmarks
        # and draw them on the image
        for (x, y) in shape:
            cv2.circle(frame, (x, y), 1, (0, 0, 255), -1)

    # show the frame
    cv2.imshow("Frame", frame)
    key = cv2.waitKey(1) & 0xFF

    # if the `q` key was pressed, break from the loop
    if key == ord("q"):
        break

# do a bit of cleanup
cv2.destroyAllWindows()
vs.stop()
def valid_bengali_letters(char):
    return ord(char) >= 2433 and ord(char) <= 2543
import dev_constants

fontDir = dev_constants.MY_PROJECT_PATH + '/Fonts/'
outDir = dev_constants.MY_PROJECT_PATH + '/Simple single letter dataset/'

fontName = 'calibri'
image = ImageCaptcha(fonts = [os.path.join(fontDir, (fontName + '.ttf'))])

exampleNum = 50000

features = []
labels = []

for counter in range(exampleNum):
    label = randint(0, 25)
    letter = '  ' + chr(np.array(label) + ord('A'))

    img = image.generate_image(letter)
    img = img.crop((0, 0, 75, 60))
    imgBW = img.convert('1')
    rowSum = 60 - np.array(imgBW).sum(0)
    rowSum = rowSum / rowSum.sum()
    rowSum = rowSum ** 2
    rowSum = rowSum / rowSum.sum()
    center = (int) (rowSum.dot(np.arange(rowSum.shape[0])))

    img = img.crop((center-20, 0, center+20, 60))
    data = np.array(img)

    features.append(data)
    labels.append(label)
Пример #60
0
# 7. 소문자 5개로 이루어진 문자열 만들기

print('a 코드 :', ord('a'))
print('b 코드 :', ord('z'))

import random

charList = []
numList = []

for i in range(5) :
    num = random.randint(97, 122)
    numList.append(num)
    char = chr(numList[i])
    charList.append(char)

str = ''.join(charList)
# '': 문자열, obj.join(): 리스트->문자열
# cf. obj.split(): 문자열->리스트

print(f'\n문자열 리스트 : {charList}')
print(f'문자열 : {str}')

# 선생님 코드
'''for i in range(5) :
    tmp = rd.randint(97, 122)
    charList.append(chr(tmp))'''