body
stringlengths 26
98.2k
| body_hash
int64 -9,222,864,604,528,158,000
9,221,803,474B
| docstring
stringlengths 1
16.8k
| path
stringlengths 5
230
| name
stringlengths 1
96
| repository_name
stringlengths 7
89
| lang
stringclasses 1
value | body_without_docstring
stringlengths 20
98.2k
|
---|---|---|---|---|---|---|---|
@commands.command(name='hoogle', brief='search hoogle')
async def hoogle(self, ctx, *query: str):
'Searches Hoggle and returns first two options\n Click title to see full search'
url = f"https://hoogle.haskell.org?mode=json&hoogle={'+'.join(query)}&start=1&count=1"
(result, error) = (await get_json(url))
if error:
(await ctx.send(error))
return
embed = discord.Embed(title=f"Definition of {' '.join(query)}", url=f"https://hoogle.haskell.org/?hoogle={'+'.join(query)}", color=self.bot.embed_color)
embed.set_thumbnail(url='https://upload.wikimedia.org/wikipedia/commons/thumb/c/c3/Lambda-letter-lowercase-symbol-Garamond.svg/1200px-Lambda-letter-lowercase-symbol-Garamond.svg.png')
if (not result):
embed.add_field(name='No results found', value='*undefined*', inline=False)
else:
for l in result:
val = (('*Module:* ' + l['module']['name']) + '\n')
val += sub('\\n{2,}', '\n\n', sub('\\n +', '\n', html2text(l['docs'])))
embed.add_field(name=html2text(l['item']), value=val, inline=False)
embed.set_footer(text='first option in Hoogle (Click title for more)')
(await ctx.send(embed=embed)) | -1,525,945,134,972,282,000 | Searches Hoggle and returns first two options
Click title to see full search | extensions/api.py | hoogle | JoseFilipeFerreira/JBB.py | python | @commands.command(name='hoogle', brief='search hoogle')
async def hoogle(self, ctx, *query: str):
'Searches Hoggle and returns first two options\n Click title to see full search'
url = f"https://hoogle.haskell.org?mode=json&hoogle={'+'.join(query)}&start=1&count=1"
(result, error) = (await get_json(url))
if error:
(await ctx.send(error))
return
embed = discord.Embed(title=f"Definition of {' '.join(query)}", url=f"https://hoogle.haskell.org/?hoogle={'+'.join(query)}", color=self.bot.embed_color)
embed.set_thumbnail(url='https://upload.wikimedia.org/wikipedia/commons/thumb/c/c3/Lambda-letter-lowercase-symbol-Garamond.svg/1200px-Lambda-letter-lowercase-symbol-Garamond.svg.png')
if (not result):
embed.add_field(name='No results found', value='*undefined*', inline=False)
else:
for l in result:
val = (('*Module:* ' + l['module']['name']) + '\n')
val += sub('\\n{2,}', '\n\n', sub('\\n +', '\n', html2text(l['docs'])))
embed.add_field(name=html2text(l['item']), value=val, inline=False)
embed.set_footer(text='first option in Hoogle (Click title for more)')
(await ctx.send(embed=embed)) |
def generateRequestData(self, offset, timestamp, chunkSize, isGroupConversation=False):
'Generate the data for the POST request.\n :return: the generated data\n '
ids_type = ('thread_fbids' if isGroupConversation else 'user_ids')
dataForm = {'messages[{}][{}][offset]'.format(ids_type, self._convID): str(offset), 'messages[{}][{}][timestamp]'.format(ids_type, self._convID): timestamp, 'messages[{}][{}][limit]'.format(ids_type, self._convID): str(chunkSize), 'client': 'web_messenger', '__a': '', '__dyn': '', '__req': '', 'fb_dtsg': self._fb_dtsg}
return dataForm | -2,812,959,289,043,096,600 | Generate the data for the POST request.
:return: the generated data | src/util/conversationScraper.py | generateRequestData | 5agado/conversation-analyzer | python | def generateRequestData(self, offset, timestamp, chunkSize, isGroupConversation=False):
'Generate the data for the POST request.\n :return: the generated data\n '
ids_type = ('thread_fbids' if isGroupConversation else 'user_ids')
dataForm = {'messages[{}][{}][offset]'.format(ids_type, self._convID): str(offset), 'messages[{}][{}][timestamp]'.format(ids_type, self._convID): timestamp, 'messages[{}][{}][limit]'.format(ids_type, self._convID): str(chunkSize), 'client': 'web_messenger', '__a': , '__dyn': , '__req': , 'fb_dtsg': self._fb_dtsg}
return dataForm |
def executeRequest(self, requestData):
'Executes the POST request and retrieves the correspondent response content.\n Request headers are generated here\n :return: the response content\n '
headers = {'Host': 'www.facebook.com', 'Origin': 'https://www.facebook.com', 'Referer': 'https://www.facebook.com', 'accept-encoding': 'gzip,deflate', 'accept-language': 'en-US,en;q=0.8', 'cookie': self._cookie, 'pragma': 'no-cache', 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.122 Safari/537.36', 'content-type': 'application/x-www-form-urlencoded', 'accept': '*/*', 'cache-control': 'no-cache'}
url = 'https://www.facebook.com/ajax/mercury/thread_info.php'
start = time.time()
response = requests.post(url, data=requestData, headers=headers)
end = time.time()
logger.info('Retrieved in {0:.2f}s'.format((end - start)))
msgsData = response.text[9:]
return msgsData | -2,882,766,584,559,465,500 | Executes the POST request and retrieves the correspondent response content.
Request headers are generated here
:return: the response content | src/util/conversationScraper.py | executeRequest | 5agado/conversation-analyzer | python | def executeRequest(self, requestData):
'Executes the POST request and retrieves the correspondent response content.\n Request headers are generated here\n :return: the response content\n '
headers = {'Host': 'www.facebook.com', 'Origin': 'https://www.facebook.com', 'Referer': 'https://www.facebook.com', 'accept-encoding': 'gzip,deflate', 'accept-language': 'en-US,en;q=0.8', 'cookie': self._cookie, 'pragma': 'no-cache', 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.122 Safari/537.36', 'content-type': 'application/x-www-form-urlencoded', 'accept': '*/*', 'cache-control': 'no-cache'}
url = 'https://www.facebook.com/ajax/mercury/thread_info.php'
start = time.time()
response = requests.post(url, data=requestData, headers=headers)
end = time.time()
logger.info('Retrieved in {0:.2f}s'.format((end - start)))
msgsData = response.text[9:]
return msgsData |
def scrapeConversation(self, merge, offset, timestampOffset, chunkSize, limit, isGroupConversation):
'Retrieves conversation messages and stores them in a JSON file\n If merge is specified, the new messages will be merged with the previous version of the conversation, if present\n '
if merge:
if (not os.path.exists(os.path.join(self._directory, 'conversation.json'))):
logger.error('Conversation not present. Merge operation not possible')
return
with open(os.path.join(self._directory, 'conversation.json')) as conv:
convMessages = json.load(conv)
numMergedMsgs = 0
if (not os.path.exists(self._directory)):
os.makedirs(self._directory)
logger.info('Starting scraping of conversation {}'.format(self._convID))
messages = []
msgsData = ''
timestamp = ('' if (timestampOffset == 0) else str(timestampOffset))
while (self.CONVERSATION_ENDMARK not in msgsData):
requestChunkSize = (chunkSize if (limit <= 0) else min(chunkSize, (limit - len(messages))))
reqData = self.generateRequestData(offset, timestamp, requestChunkSize, isGroupConversation)
logger.info('Retrieving messages {}-{}'.format(offset, (requestChunkSize + offset)))
msgsData = self.executeRequest(reqData)
jsonData = json.loads(msgsData)
if (jsonData and ('payload' in jsonData) and jsonData['payload']):
if (('actions' in jsonData['payload']) and jsonData['payload']['actions']):
actions = jsonData['payload']['actions']
if (merge and (convMessages[(- 1)]['timestamp'] > actions[0]['timestamp'])):
for (i, action) in enumerate(actions):
if (convMessages[(- 1)]['timestamp'] == actions[i]['timestamp']):
numMergedMsgs = (len(actions[(i + 1):(- 1)]) + len(messages))
messages = ((convMessages + actions[(i + 1):(- 1)]) + messages)
break
break
if (len(messages) == 0):
messages = actions
else:
messages = (actions[:(- 1)] + messages)
timestamp = str(actions[0]['timestamp'])
else:
if ('errorSummary' in jsonData):
logger.error(('Response error: ' + jsonData['errorSummary']))
else:
logger.error('Response error. No messages found')
logger.error(msgsData)
return
else:
logger.error('Response error. Empty data or payload')
logger.error(msgsData)
logger.info('Retrying in {} seconds'.format(self.ERROR_WAIT))
time.sleep(self.ERROR_WAIT)
continue
offset += chunkSize
if ((limit != 0) and (len(messages) >= limit)):
break
time.sleep(self.REQUEST_WAIT)
if merge:
logger.info('Successfully merged {} new messages'.format(numMergedMsgs))
logger.info('Conversation total message count = {}'.format(len(messages)))
else:
logger.info('Conversation scraped successfully. {} messages retrieved'.format(len(messages)))
self.writeMessages(messages) | -4,032,054,314,809,956,000 | Retrieves conversation messages and stores them in a JSON file
If merge is specified, the new messages will be merged with the previous version of the conversation, if present | src/util/conversationScraper.py | scrapeConversation | 5agado/conversation-analyzer | python | def scrapeConversation(self, merge, offset, timestampOffset, chunkSize, limit, isGroupConversation):
'Retrieves conversation messages and stores them in a JSON file\n If merge is specified, the new messages will be merged with the previous version of the conversation, if present\n '
if merge:
if (not os.path.exists(os.path.join(self._directory, 'conversation.json'))):
logger.error('Conversation not present. Merge operation not possible')
return
with open(os.path.join(self._directory, 'conversation.json')) as conv:
convMessages = json.load(conv)
numMergedMsgs = 0
if (not os.path.exists(self._directory)):
os.makedirs(self._directory)
logger.info('Starting scraping of conversation {}'.format(self._convID))
messages = []
msgsData =
timestamp = ( if (timestampOffset == 0) else str(timestampOffset))
while (self.CONVERSATION_ENDMARK not in msgsData):
requestChunkSize = (chunkSize if (limit <= 0) else min(chunkSize, (limit - len(messages))))
reqData = self.generateRequestData(offset, timestamp, requestChunkSize, isGroupConversation)
logger.info('Retrieving messages {}-{}'.format(offset, (requestChunkSize + offset)))
msgsData = self.executeRequest(reqData)
jsonData = json.loads(msgsData)
if (jsonData and ('payload' in jsonData) and jsonData['payload']):
if (('actions' in jsonData['payload']) and jsonData['payload']['actions']):
actions = jsonData['payload']['actions']
if (merge and (convMessages[(- 1)]['timestamp'] > actions[0]['timestamp'])):
for (i, action) in enumerate(actions):
if (convMessages[(- 1)]['timestamp'] == actions[i]['timestamp']):
numMergedMsgs = (len(actions[(i + 1):(- 1)]) + len(messages))
messages = ((convMessages + actions[(i + 1):(- 1)]) + messages)
break
break
if (len(messages) == 0):
messages = actions
else:
messages = (actions[:(- 1)] + messages)
timestamp = str(actions[0]['timestamp'])
else:
if ('errorSummary' in jsonData):
logger.error(('Response error: ' + jsonData['errorSummary']))
else:
logger.error('Response error. No messages found')
logger.error(msgsData)
return
else:
logger.error('Response error. Empty data or payload')
logger.error(msgsData)
logger.info('Retrying in {} seconds'.format(self.ERROR_WAIT))
time.sleep(self.ERROR_WAIT)
continue
offset += chunkSize
if ((limit != 0) and (len(messages) >= limit)):
break
time.sleep(self.REQUEST_WAIT)
if merge:
logger.info('Successfully merged {} new messages'.format(numMergedMsgs))
logger.info('Conversation total message count = {}'.format(len(messages)))
else:
logger.info('Conversation scraped successfully. {} messages retrieved'.format(len(messages)))
self.writeMessages(messages) |
def check_num_list(prompt: str, max_length: int=0, min_length: int=0) -> List[float]:
'Function to check if users input is a number, splitting number\n by spaces and checking that the correct amount of numbers are\n entered, returning them in a list'
while True:
try:
num = input(prompt)
num = num.split(' ')
if min_length:
assert (len(num) >= min_length), f'Please enter at least {min_length} numbers'
if max_length:
assert (len(num) <= max_length), f'Please enter no more than {max_length} numbers'
for (index, value) in enumerate(num):
num[index] = float(value)
return num
except Exception as e:
print(e) | -5,256,720,275,051,967,000 | Function to check if users input is a number, splitting number
by spaces and checking that the correct amount of numbers are
entered, returning them in a list | 150-Challenges/Challenges 27 - 34/Challenge 33.py | check_num_list | DGrifferty/Python | python | def check_num_list(prompt: str, max_length: int=0, min_length: int=0) -> List[float]:
'Function to check if users input is a number, splitting number\n by spaces and checking that the correct amount of numbers are\n entered, returning them in a list'
while True:
try:
num = input(prompt)
num = num.split(' ')
if min_length:
assert (len(num) >= min_length), f'Please enter at least {min_length} numbers'
if max_length:
assert (len(num) <= max_length), f'Please enter no more than {max_length} numbers'
for (index, value) in enumerate(num):
num[index] = float(value)
return num
except Exception as e:
print(e) |
def get_imdb(name):
'Get an imdb (image database) by name.'
if (name not in __sets):
raise KeyError('Unknown dataset: {}'.format(name))
return __sets[name]() | -3,263,413,934,054,098,000 | Get an imdb (image database) by name. | lib/datasets/factory.py | get_imdb | wangvation/torch-mobilenet | python | def get_imdb(name):
if (name not in __sets):
raise KeyError('Unknown dataset: {}'.format(name))
return __sets[name]() |
def list_imdbs():
'List all registered imdbs.'
return list(__sets.keys()) | 4,693,669,182,354,276,000 | List all registered imdbs. | lib/datasets/factory.py | list_imdbs | wangvation/torch-mobilenet | python | def list_imdbs():
return list(__sets.keys()) |
def main(*args):
'\n Process command line arguments and invoke bot.\n\n If args is an empty list, sys.argv is used.\n\n @param args: command line arguments\n @type args: str\n '
filename = 'fb2w.nt.gz'
for arg in pywikibot.handle_args(args):
if arg.startswith('-filename'):
filename = arg[11:]
bot = FreebaseMapperRobot(filename)
bot.run() | 8,901,002,085,312,635,000 | Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
@param args: command line arguments
@type args: str | scripts/freebasemappingupload.py | main | 5j9/pywikibot-core | python | def main(*args):
'\n Process command line arguments and invoke bot.\n\n If args is an empty list, sys.argv is used.\n\n @param args: command line arguments\n @type args: str\n '
filename = 'fb2w.nt.gz'
for arg in pywikibot.handle_args(args):
if arg.startswith('-filename'):
filename = arg[11:]
bot = FreebaseMapperRobot(filename)
bot.run() |
def __init__(self, filename):
'Initializer.'
self.repo = pywikibot.Site('wikidata', 'wikidata').data_repository()
self.filename = filename
if (not os.path.exists(self.filename)):
pywikibot.output(('Cannot find %s. Try providing the absolute path.' % self.filename))
sys.exit(1) | 8,991,422,563,458,918,000 | Initializer. | scripts/freebasemappingupload.py | __init__ | 5j9/pywikibot-core | python | def __init__(self, filename):
self.repo = pywikibot.Site('wikidata', 'wikidata').data_repository()
self.filename = filename
if (not os.path.exists(self.filename)):
pywikibot.output(('Cannot find %s. Try providing the absolute path.' % self.filename))
sys.exit(1) |
def run(self):
'Run the bot.'
self.claim = pywikibot.Claim(self.repo, 'P646')
self.statedin = pywikibot.Claim(self.repo, 'P248')
freebasedumpitem = pywikibot.ItemPage(self.repo, 'Q15241312')
self.statedin.setTarget(freebasedumpitem)
self.dateofpub = pywikibot.Claim(self.repo, 'P577')
oct28 = pywikibot.WbTime(site=self.repo, year=2013, month=10, day=28, precision='day')
self.dateofpub.setTarget(oct28)
for line in gzip.open(self.filename):
self.processLine(line.strip()) | -7,101,836,632,625,595,000 | Run the bot. | scripts/freebasemappingupload.py | run | 5j9/pywikibot-core | python | def run(self):
self.claim = pywikibot.Claim(self.repo, 'P646')
self.statedin = pywikibot.Claim(self.repo, 'P248')
freebasedumpitem = pywikibot.ItemPage(self.repo, 'Q15241312')
self.statedin.setTarget(freebasedumpitem)
self.dateofpub = pywikibot.Claim(self.repo, 'P577')
oct28 = pywikibot.WbTime(site=self.repo, year=2013, month=10, day=28, precision='day')
self.dateofpub.setTarget(oct28)
for line in gzip.open(self.filename):
self.processLine(line.strip()) |
def processLine(self, line):
'Process a single line.'
if ((not line) or line.startswith('#')):
return
(mid, sameas, qid, dot) = line.split()
if (sameas != '<https://www.w3.org/2002/07/owl#sameAs>'):
return
if (dot != '.'):
return
if (not mid.startswith('<https://rdf.freebase.com/ns/m')):
return
mid = ('/m/' + mid[30:(- 1)])
if (not qid.startswith('<https://www.wikidata.org/entity/Q')):
return
qid = ('Q' + qid[33:(- 1)])
data = pywikibot.ItemPage(self.repo, qid)
data.get()
if (not data.labels):
label = ''
elif ('en' in data.labels):
label = data.labels['en']
else:
label = list(data.labels.values())[0]
pywikibot.output('Parsed: {} <--> {}'.format(qid, mid))
pywikibot.output('{} is {}'.format(data.getID(), label))
if (data.claims and ('P646' in data.claims)):
if (mid != data.claims['P646'][0].getTarget()):
pywikibot.output('Mismatch: expected {}, has {} instead'.format(mid, data.claims['P646'][0].getTarget()))
else:
pywikibot.output('Already has mid set, is consistent.')
else:
pywikibot.output('Going to add a new claim.')
self.claim.setTarget(mid)
data.addClaim(self.claim)
self.claim.addSources([self.statedin, self.dateofpub])
pywikibot.output('Claim added!') | 3,031,414,387,276,538,400 | Process a single line. | scripts/freebasemappingupload.py | processLine | 5j9/pywikibot-core | python | def processLine(self, line):
if ((not line) or line.startswith('#')):
return
(mid, sameas, qid, dot) = line.split()
if (sameas != '<https://www.w3.org/2002/07/owl#sameAs>'):
return
if (dot != '.'):
return
if (not mid.startswith('<https://rdf.freebase.com/ns/m')):
return
mid = ('/m/' + mid[30:(- 1)])
if (not qid.startswith('<https://www.wikidata.org/entity/Q')):
return
qid = ('Q' + qid[33:(- 1)])
data = pywikibot.ItemPage(self.repo, qid)
data.get()
if (not data.labels):
label =
elif ('en' in data.labels):
label = data.labels['en']
else:
label = list(data.labels.values())[0]
pywikibot.output('Parsed: {} <--> {}'.format(qid, mid))
pywikibot.output('{} is {}'.format(data.getID(), label))
if (data.claims and ('P646' in data.claims)):
if (mid != data.claims['P646'][0].getTarget()):
pywikibot.output('Mismatch: expected {}, has {} instead'.format(mid, data.claims['P646'][0].getTarget()))
else:
pywikibot.output('Already has mid set, is consistent.')
else:
pywikibot.output('Going to add a new claim.')
self.claim.setTarget(mid)
data.addClaim(self.claim)
self.claim.addSources([self.statedin, self.dateofpub])
pywikibot.output('Claim added!') |
def _parse_decl_specs_simple(self, outer: str, typed: bool) -> ASTDeclSpecsSimple:
'Just parse the simple ones.'
storage = None
threadLocal = None
inline = None
virtual = None
explicit = None
constexpr = None
volatile = None
const = None
friend = None
attrs = []
while 1:
self.skip_ws()
if (not storage):
if (outer in ('member', 'function')):
if self.skip_word('static'):
storage = 'static'
continue
if self.skip_word('extern'):
storage = 'extern'
continue
if (outer == 'member'):
if self.skip_word('mutable'):
storage = 'mutable'
continue
if self.skip_word('register'):
storage = 'register'
continue
if ((not threadLocal) and (outer == 'member')):
threadLocal = self.skip_word('thread_local')
if threadLocal:
continue
if (outer == 'function'):
if (not inline):
inline = self.skip_word('inline')
if inline:
continue
if (not friend):
friend = self.skip_word('friend')
if friend:
continue
if (not virtual):
virtual = self.skip_word('virtual')
if virtual:
continue
if (not explicit):
explicit = self.skip_word('explicit')
if explicit:
continue
if ((not constexpr) and (outer in ('member', 'function'))):
constexpr = self.skip_word('constexpr')
if constexpr:
continue
if ((not volatile) and typed):
volatile = self.skip_word('volatile')
if volatile:
continue
if ((not const) and typed):
const = self.skip_word('const')
if const:
continue
attr = self._parse_attribute()
if attr:
attrs.append(attr)
continue
break
return ASTDeclSpecsSimple(storage, threadLocal, inline, virtual, explicit, constexpr, volatile, const, friend, attrs) | 489,535,564,035,447,300 | Just parse the simple ones. | sphinx/domains/cpp.py | _parse_decl_specs_simple | begolu2/sphinx | python | def _parse_decl_specs_simple(self, outer: str, typed: bool) -> ASTDeclSpecsSimple:
storage = None
threadLocal = None
inline = None
virtual = None
explicit = None
constexpr = None
volatile = None
const = None
friend = None
attrs = []
while 1:
self.skip_ws()
if (not storage):
if (outer in ('member', 'function')):
if self.skip_word('static'):
storage = 'static'
continue
if self.skip_word('extern'):
storage = 'extern'
continue
if (outer == 'member'):
if self.skip_word('mutable'):
storage = 'mutable'
continue
if self.skip_word('register'):
storage = 'register'
continue
if ((not threadLocal) and (outer == 'member')):
threadLocal = self.skip_word('thread_local')
if threadLocal:
continue
if (outer == 'function'):
if (not inline):
inline = self.skip_word('inline')
if inline:
continue
if (not friend):
friend = self.skip_word('friend')
if friend:
continue
if (not virtual):
virtual = self.skip_word('virtual')
if virtual:
continue
if (not explicit):
explicit = self.skip_word('explicit')
if explicit:
continue
if ((not constexpr) and (outer in ('member', 'function'))):
constexpr = self.skip_word('constexpr')
if constexpr:
continue
if ((not volatile) and typed):
volatile = self.skip_word('volatile')
if volatile:
continue
if ((not const) and typed):
const = self.skip_word('const')
if const:
continue
attr = self._parse_attribute()
if attr:
attrs.append(attr)
continue
break
return ASTDeclSpecsSimple(storage, threadLocal, inline, virtual, explicit, constexpr, volatile, const, friend, attrs) |
def _parse_type(self, named: Union[(bool, str)], outer: str=None) -> ASTType:
"\n named=False|'maybe'|True: 'maybe' is e.g., for function objects which\n doesn't need to name the arguments\n\n outer == operatorCast: annoying case, we should not take the params\n "
if outer:
if (outer not in ('type', 'member', 'function', 'operatorCast', 'templateParam')):
raise Exception(('Internal error, unknown outer "%s".' % outer))
if (outer != 'operatorCast'):
assert named
if (outer in ('type', 'function')):
prevErrors = []
startPos = self.pos
try:
declSpecs = self._parse_decl_specs(outer=outer, typed=False)
decl = self._parse_declarator(named=True, paramMode=outer, typed=False)
self.assert_end()
except DefinitionError as exUntyped:
if (outer == 'type'):
desc = 'If just a name'
elif (outer == 'function'):
desc = 'If the function has no return type'
else:
assert False
prevErrors.append((exUntyped, desc))
self.pos = startPos
try:
declSpecs = self._parse_decl_specs(outer=outer)
decl = self._parse_declarator(named=True, paramMode=outer)
except DefinitionError as exTyped:
self.pos = startPos
if (outer == 'type'):
desc = 'If typedef-like declaration'
elif (outer == 'function'):
desc = 'If the function has a return type'
else:
assert False
prevErrors.append((exTyped, desc))
if True:
if (outer == 'type'):
header = 'Type must be either just a name or a '
header += 'typedef-like declaration.'
elif (outer == 'function'):
header = 'Error when parsing function declaration.'
else:
assert False
raise self._make_multi_error(prevErrors, header)
else:
self.pos = startPos
typed = True
declSpecs = self._parse_decl_specs(outer=outer, typed=typed)
decl = self._parse_declarator(named=True, paramMode=outer, typed=typed)
else:
paramMode = 'type'
if (outer == 'member'):
named = True
elif (outer == 'operatorCast'):
paramMode = 'operatorCast'
outer = None
elif (outer == 'templateParam'):
named = 'single'
declSpecs = self._parse_decl_specs(outer=outer)
decl = self._parse_declarator(named=named, paramMode=paramMode)
return ASTType(declSpecs, decl) | -6,564,301,317,631,929,000 | named=False|'maybe'|True: 'maybe' is e.g., for function objects which
doesn't need to name the arguments
outer == operatorCast: annoying case, we should not take the params | sphinx/domains/cpp.py | _parse_type | begolu2/sphinx | python | def _parse_type(self, named: Union[(bool, str)], outer: str=None) -> ASTType:
"\n named=False|'maybe'|True: 'maybe' is e.g., for function objects which\n doesn't need to name the arguments\n\n outer == operatorCast: annoying case, we should not take the params\n "
if outer:
if (outer not in ('type', 'member', 'function', 'operatorCast', 'templateParam')):
raise Exception(('Internal error, unknown outer "%s".' % outer))
if (outer != 'operatorCast'):
assert named
if (outer in ('type', 'function')):
prevErrors = []
startPos = self.pos
try:
declSpecs = self._parse_decl_specs(outer=outer, typed=False)
decl = self._parse_declarator(named=True, paramMode=outer, typed=False)
self.assert_end()
except DefinitionError as exUntyped:
if (outer == 'type'):
desc = 'If just a name'
elif (outer == 'function'):
desc = 'If the function has no return type'
else:
assert False
prevErrors.append((exUntyped, desc))
self.pos = startPos
try:
declSpecs = self._parse_decl_specs(outer=outer)
decl = self._parse_declarator(named=True, paramMode=outer)
except DefinitionError as exTyped:
self.pos = startPos
if (outer == 'type'):
desc = 'If typedef-like declaration'
elif (outer == 'function'):
desc = 'If the function has a return type'
else:
assert False
prevErrors.append((exTyped, desc))
if True:
if (outer == 'type'):
header = 'Type must be either just a name or a '
header += 'typedef-like declaration.'
elif (outer == 'function'):
header = 'Error when parsing function declaration.'
else:
assert False
raise self._make_multi_error(prevErrors, header)
else:
self.pos = startPos
typed = True
declSpecs = self._parse_decl_specs(outer=outer, typed=typed)
decl = self._parse_declarator(named=True, paramMode=outer, typed=typed)
else:
paramMode = 'type'
if (outer == 'member'):
named = True
elif (outer == 'operatorCast'):
paramMode = 'operatorCast'
outer = None
elif (outer == 'templateParam'):
named = 'single'
declSpecs = self._parse_decl_specs(outer=outer)
decl = self._parse_declarator(named=named, paramMode=paramMode)
return ASTType(declSpecs, decl) |
def run(self) -> List[Node]:
"\n On purpose this doesn't call the ObjectDescription version, but is based on it.\n Each alias signature may expand into multiple real signatures (an overload set).\n The code is therefore based on the ObjectDescription version.\n "
if (':' in self.name):
(self.domain, self.objtype) = self.name.split(':', 1)
else:
(self.domain, self.objtype) = ('', self.name)
node = addnodes.desc()
node.document = self.state.document
node['domain'] = self.domain
node['objtype'] = node['desctype'] = self.objtype
node['noindex'] = True
self.names = []
signatures = self.get_signatures()
for (i, sig) in enumerate(signatures):
node.append(AliasNode(sig, env=self.env))
contentnode = addnodes.desc_content()
node.append(contentnode)
self.before_content()
self.state.nested_parse(self.content, self.content_offset, contentnode)
self.env.temp_data['object'] = None
self.after_content()
return [node] | -4,870,467,569,921,633,000 | On purpose this doesn't call the ObjectDescription version, but is based on it.
Each alias signature may expand into multiple real signatures (an overload set).
The code is therefore based on the ObjectDescription version. | sphinx/domains/cpp.py | run | begolu2/sphinx | python | def run(self) -> List[Node]:
"\n On purpose this doesn't call the ObjectDescription version, but is based on it.\n Each alias signature may expand into multiple real signatures (an overload set).\n The code is therefore based on the ObjectDescription version.\n "
if (':' in self.name):
(self.domain, self.objtype) = self.name.split(':', 1)
else:
(self.domain, self.objtype) = (, self.name)
node = addnodes.desc()
node.document = self.state.document
node['domain'] = self.domain
node['objtype'] = node['desctype'] = self.objtype
node['noindex'] = True
self.names = []
signatures = self.get_signatures()
for (i, sig) in enumerate(signatures):
node.append(AliasNode(sig, env=self.env))
contentnode = addnodes.desc_content()
node.append(contentnode)
self.before_content()
self.state.nested_parse(self.content, self.content_offset, contentnode)
self.env.temp_data['object'] = None
self.after_content()
return [node] |
def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions]=None, dynamic_tags_json: Optional[pulumi.Input[str]]=None, is_push_enabled: Optional[pulumi.Input[bool]]=None, kind: Optional[pulumi.Input[str]]=None, name: Optional[pulumi.Input[str]]=None, resource_group_name: Optional[pulumi.Input[str]]=None, slot: Optional[pulumi.Input[str]]=None, tag_whitelist_json: Optional[pulumi.Input[str]]=None, tags_requiring_auth: Optional[pulumi.Input[str]]=None, __props__=None, __name__=None, __opts__=None):
"\n Push settings for the App.\n\n :param str resource_name: The name of the resource.\n :param pulumi.ResourceOptions opts: Options for the resource.\n :param pulumi.Input[str] dynamic_tags_json: Gets or sets a JSON string containing a list of dynamic tags that will be evaluated from user claims in the push registration endpoint.\n :param pulumi.Input[bool] is_push_enabled: Gets or sets a flag indicating whether the Push endpoint is enabled.\n :param pulumi.Input[str] kind: Kind of resource.\n :param pulumi.Input[str] name: Name of web app.\n :param pulumi.Input[str] resource_group_name: Name of the resource group to which the resource belongs.\n :param pulumi.Input[str] slot: Name of web app slot. If not specified then will default to production slot.\n :param pulumi.Input[str] tag_whitelist_json: Gets or sets a JSON string containing a list of tags that are whitelisted for use by the push registration endpoint.\n :param pulumi.Input[str] tags_requiring_auth: Gets or sets a JSON string containing a list of tags that require user authentication to be used in the push registration endpoint.\n Tags can consist of alphanumeric characters and the following:\n '_', '@', '#', '.', ':', '-'. \n Validation should be performed at the PushRequestHandler.\n "
if (__name__ is not None):
warnings.warn('explicit use of __name__ is deprecated', DeprecationWarning)
resource_name = __name__
if (__opts__ is not None):
warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)
opts = __opts__
if (opts is None):
opts = pulumi.ResourceOptions()
if (not isinstance(opts, pulumi.ResourceOptions)):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if (opts.version is None):
opts.version = _utilities.get_version()
if (opts.id is None):
if (__props__ is not None):
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = dict()
__props__['dynamic_tags_json'] = dynamic_tags_json
if ((is_push_enabled is None) and (not opts.urn)):
raise TypeError("Missing required property 'is_push_enabled'")
__props__['is_push_enabled'] = is_push_enabled
__props__['kind'] = kind
if ((name is None) and (not opts.urn)):
raise TypeError("Missing required property 'name'")
__props__['name'] = name
if ((resource_group_name is None) and (not opts.urn)):
raise TypeError("Missing required property 'resource_group_name'")
__props__['resource_group_name'] = resource_group_name
if ((slot is None) and (not opts.urn)):
raise TypeError("Missing required property 'slot'")
__props__['slot'] = slot
__props__['tag_whitelist_json'] = tag_whitelist_json
__props__['tags_requiring_auth'] = tags_requiring_auth
__props__['system_data'] = None
__props__['type'] = None
alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_='azure-nextgen:web/v20200901:WebAppSitePushSettingsSlot'), pulumi.Alias(type_='azure-native:web:WebAppSitePushSettingsSlot'), pulumi.Alias(type_='azure-nextgen:web:WebAppSitePushSettingsSlot'), pulumi.Alias(type_='azure-native:web/latest:WebAppSitePushSettingsSlot'), pulumi.Alias(type_='azure-nextgen:web/latest:WebAppSitePushSettingsSlot'), pulumi.Alias(type_='azure-native:web/v20160801:WebAppSitePushSettingsSlot'), pulumi.Alias(type_='azure-nextgen:web/v20160801:WebAppSitePushSettingsSlot'), pulumi.Alias(type_='azure-native:web/v20180201:WebAppSitePushSettingsSlot'), pulumi.Alias(type_='azure-nextgen:web/v20180201:WebAppSitePushSettingsSlot'), pulumi.Alias(type_='azure-native:web/v20181101:WebAppSitePushSettingsSlot'), pulumi.Alias(type_='azure-nextgen:web/v20181101:WebAppSitePushSettingsSlot'), pulumi.Alias(type_='azure-native:web/v20190801:WebAppSitePushSettingsSlot'), pulumi.Alias(type_='azure-nextgen:web/v20190801:WebAppSitePushSettingsSlot'), pulumi.Alias(type_='azure-native:web/v20200601:WebAppSitePushSettingsSlot'), pulumi.Alias(type_='azure-nextgen:web/v20200601:WebAppSitePushSettingsSlot'), pulumi.Alias(type_='azure-native:web/v20201001:WebAppSitePushSettingsSlot'), pulumi.Alias(type_='azure-nextgen:web/v20201001:WebAppSitePushSettingsSlot')])
opts = pulumi.ResourceOptions.merge(opts, alias_opts)
super(WebAppSitePushSettingsSlot, __self__).__init__('azure-native:web/v20200901:WebAppSitePushSettingsSlot', resource_name, __props__, opts) | -8,120,773,970,255,479,000 | Push settings for the App.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] dynamic_tags_json: Gets or sets a JSON string containing a list of dynamic tags that will be evaluated from user claims in the push registration endpoint.
:param pulumi.Input[bool] is_push_enabled: Gets or sets a flag indicating whether the Push endpoint is enabled.
:param pulumi.Input[str] kind: Kind of resource.
:param pulumi.Input[str] name: Name of web app.
:param pulumi.Input[str] resource_group_name: Name of the resource group to which the resource belongs.
:param pulumi.Input[str] slot: Name of web app slot. If not specified then will default to production slot.
:param pulumi.Input[str] tag_whitelist_json: Gets or sets a JSON string containing a list of tags that are whitelisted for use by the push registration endpoint.
:param pulumi.Input[str] tags_requiring_auth: Gets or sets a JSON string containing a list of tags that require user authentication to be used in the push registration endpoint.
Tags can consist of alphanumeric characters and the following:
'_', '@', '#', '.', ':', '-'.
Validation should be performed at the PushRequestHandler. | sdk/python/pulumi_azure_native/web/v20200901/web_app_site_push_settings_slot.py | __init__ | pulumi-bot/pulumi-azure-native | python | def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions]=None, dynamic_tags_json: Optional[pulumi.Input[str]]=None, is_push_enabled: Optional[pulumi.Input[bool]]=None, kind: Optional[pulumi.Input[str]]=None, name: Optional[pulumi.Input[str]]=None, resource_group_name: Optional[pulumi.Input[str]]=None, slot: Optional[pulumi.Input[str]]=None, tag_whitelist_json: Optional[pulumi.Input[str]]=None, tags_requiring_auth: Optional[pulumi.Input[str]]=None, __props__=None, __name__=None, __opts__=None):
"\n Push settings for the App.\n\n :param str resource_name: The name of the resource.\n :param pulumi.ResourceOptions opts: Options for the resource.\n :param pulumi.Input[str] dynamic_tags_json: Gets or sets a JSON string containing a list of dynamic tags that will be evaluated from user claims in the push registration endpoint.\n :param pulumi.Input[bool] is_push_enabled: Gets or sets a flag indicating whether the Push endpoint is enabled.\n :param pulumi.Input[str] kind: Kind of resource.\n :param pulumi.Input[str] name: Name of web app.\n :param pulumi.Input[str] resource_group_name: Name of the resource group to which the resource belongs.\n :param pulumi.Input[str] slot: Name of web app slot. If not specified then will default to production slot.\n :param pulumi.Input[str] tag_whitelist_json: Gets or sets a JSON string containing a list of tags that are whitelisted for use by the push registration endpoint.\n :param pulumi.Input[str] tags_requiring_auth: Gets or sets a JSON string containing a list of tags that require user authentication to be used in the push registration endpoint.\n Tags can consist of alphanumeric characters and the following:\n '_', '@', '#', '.', ':', '-'. \n Validation should be performed at the PushRequestHandler.\n "
if (__name__ is not None):
warnings.warn('explicit use of __name__ is deprecated', DeprecationWarning)
resource_name = __name__
if (__opts__ is not None):
warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)
opts = __opts__
if (opts is None):
opts = pulumi.ResourceOptions()
if (not isinstance(opts, pulumi.ResourceOptions)):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if (opts.version is None):
opts.version = _utilities.get_version()
if (opts.id is None):
if (__props__ is not None):
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = dict()
__props__['dynamic_tags_json'] = dynamic_tags_json
if ((is_push_enabled is None) and (not opts.urn)):
raise TypeError("Missing required property 'is_push_enabled'")
__props__['is_push_enabled'] = is_push_enabled
__props__['kind'] = kind
if ((name is None) and (not opts.urn)):
raise TypeError("Missing required property 'name'")
__props__['name'] = name
if ((resource_group_name is None) and (not opts.urn)):
raise TypeError("Missing required property 'resource_group_name'")
__props__['resource_group_name'] = resource_group_name
if ((slot is None) and (not opts.urn)):
raise TypeError("Missing required property 'slot'")
__props__['slot'] = slot
__props__['tag_whitelist_json'] = tag_whitelist_json
__props__['tags_requiring_auth'] = tags_requiring_auth
__props__['system_data'] = None
__props__['type'] = None
alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_='azure-nextgen:web/v20200901:WebAppSitePushSettingsSlot'), pulumi.Alias(type_='azure-native:web:WebAppSitePushSettingsSlot'), pulumi.Alias(type_='azure-nextgen:web:WebAppSitePushSettingsSlot'), pulumi.Alias(type_='azure-native:web/latest:WebAppSitePushSettingsSlot'), pulumi.Alias(type_='azure-nextgen:web/latest:WebAppSitePushSettingsSlot'), pulumi.Alias(type_='azure-native:web/v20160801:WebAppSitePushSettingsSlot'), pulumi.Alias(type_='azure-nextgen:web/v20160801:WebAppSitePushSettingsSlot'), pulumi.Alias(type_='azure-native:web/v20180201:WebAppSitePushSettingsSlot'), pulumi.Alias(type_='azure-nextgen:web/v20180201:WebAppSitePushSettingsSlot'), pulumi.Alias(type_='azure-native:web/v20181101:WebAppSitePushSettingsSlot'), pulumi.Alias(type_='azure-nextgen:web/v20181101:WebAppSitePushSettingsSlot'), pulumi.Alias(type_='azure-native:web/v20190801:WebAppSitePushSettingsSlot'), pulumi.Alias(type_='azure-nextgen:web/v20190801:WebAppSitePushSettingsSlot'), pulumi.Alias(type_='azure-native:web/v20200601:WebAppSitePushSettingsSlot'), pulumi.Alias(type_='azure-nextgen:web/v20200601:WebAppSitePushSettingsSlot'), pulumi.Alias(type_='azure-native:web/v20201001:WebAppSitePushSettingsSlot'), pulumi.Alias(type_='azure-nextgen:web/v20201001:WebAppSitePushSettingsSlot')])
opts = pulumi.ResourceOptions.merge(opts, alias_opts)
super(WebAppSitePushSettingsSlot, __self__).__init__('azure-native:web/v20200901:WebAppSitePushSettingsSlot', resource_name, __props__, opts) |
@staticmethod
def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions]=None) -> 'WebAppSitePushSettingsSlot':
"\n Get an existing WebAppSitePushSettingsSlot resource's state with the given name, id, and optional extra\n properties used to qualify the lookup.\n\n :param str resource_name: The unique name of the resulting resource.\n :param pulumi.Input[str] id: The unique provider ID of the resource to lookup.\n :param pulumi.ResourceOptions opts: Options for the resource.\n "
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = dict()
__props__['dynamic_tags_json'] = None
__props__['is_push_enabled'] = None
__props__['kind'] = None
__props__['name'] = None
__props__['system_data'] = None
__props__['tag_whitelist_json'] = None
__props__['tags_requiring_auth'] = None
__props__['type'] = None
return WebAppSitePushSettingsSlot(resource_name, opts=opts, __props__=__props__) | -3,682,211,527,570,844,700 | Get an existing WebAppSitePushSettingsSlot resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource. | sdk/python/pulumi_azure_native/web/v20200901/web_app_site_push_settings_slot.py | get | pulumi-bot/pulumi-azure-native | python | @staticmethod
def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions]=None) -> 'WebAppSitePushSettingsSlot':
"\n Get an existing WebAppSitePushSettingsSlot resource's state with the given name, id, and optional extra\n properties used to qualify the lookup.\n\n :param str resource_name: The unique name of the resulting resource.\n :param pulumi.Input[str] id: The unique provider ID of the resource to lookup.\n :param pulumi.ResourceOptions opts: Options for the resource.\n "
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = dict()
__props__['dynamic_tags_json'] = None
__props__['is_push_enabled'] = None
__props__['kind'] = None
__props__['name'] = None
__props__['system_data'] = None
__props__['tag_whitelist_json'] = None
__props__['tags_requiring_auth'] = None
__props__['type'] = None
return WebAppSitePushSettingsSlot(resource_name, opts=opts, __props__=__props__) |
@property
@pulumi.getter(name='dynamicTagsJson')
def dynamic_tags_json(self) -> pulumi.Output[Optional[str]]:
'\n Gets or sets a JSON string containing a list of dynamic tags that will be evaluated from user claims in the push registration endpoint.\n '
return pulumi.get(self, 'dynamic_tags_json') | 2,910,655,291,979,059,000 | Gets or sets a JSON string containing a list of dynamic tags that will be evaluated from user claims in the push registration endpoint. | sdk/python/pulumi_azure_native/web/v20200901/web_app_site_push_settings_slot.py | dynamic_tags_json | pulumi-bot/pulumi-azure-native | python | @property
@pulumi.getter(name='dynamicTagsJson')
def dynamic_tags_json(self) -> pulumi.Output[Optional[str]]:
'\n \n '
return pulumi.get(self, 'dynamic_tags_json') |
@property
@pulumi.getter(name='isPushEnabled')
def is_push_enabled(self) -> pulumi.Output[bool]:
'\n Gets or sets a flag indicating whether the Push endpoint is enabled.\n '
return pulumi.get(self, 'is_push_enabled') | 4,037,824,550,830,096,400 | Gets or sets a flag indicating whether the Push endpoint is enabled. | sdk/python/pulumi_azure_native/web/v20200901/web_app_site_push_settings_slot.py | is_push_enabled | pulumi-bot/pulumi-azure-native | python | @property
@pulumi.getter(name='isPushEnabled')
def is_push_enabled(self) -> pulumi.Output[bool]:
'\n \n '
return pulumi.get(self, 'is_push_enabled') |
@property
@pulumi.getter
def kind(self) -> pulumi.Output[Optional[str]]:
'\n Kind of resource.\n '
return pulumi.get(self, 'kind') | -1,425,049,396,835,993,600 | Kind of resource. | sdk/python/pulumi_azure_native/web/v20200901/web_app_site_push_settings_slot.py | kind | pulumi-bot/pulumi-azure-native | python | @property
@pulumi.getter
def kind(self) -> pulumi.Output[Optional[str]]:
'\n \n '
return pulumi.get(self, 'kind') |
@property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
'\n Resource Name.\n '
return pulumi.get(self, 'name') | 1,193,115,514,403,237,400 | Resource Name. | sdk/python/pulumi_azure_native/web/v20200901/web_app_site_push_settings_slot.py | name | pulumi-bot/pulumi-azure-native | python | @property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
'\n \n '
return pulumi.get(self, 'name') |
@property
@pulumi.getter(name='systemData')
def system_data(self) -> pulumi.Output['outputs.SystemDataResponse']:
'\n The system metadata relating to this resource.\n '
return pulumi.get(self, 'system_data') | -7,169,214,494,930,004,000 | The system metadata relating to this resource. | sdk/python/pulumi_azure_native/web/v20200901/web_app_site_push_settings_slot.py | system_data | pulumi-bot/pulumi-azure-native | python | @property
@pulumi.getter(name='systemData')
def system_data(self) -> pulumi.Output['outputs.SystemDataResponse']:
'\n \n '
return pulumi.get(self, 'system_data') |
@property
@pulumi.getter(name='tagWhitelistJson')
def tag_whitelist_json(self) -> pulumi.Output[Optional[str]]:
'\n Gets or sets a JSON string containing a list of tags that are whitelisted for use by the push registration endpoint.\n '
return pulumi.get(self, 'tag_whitelist_json') | -212,308,369,731,080,420 | Gets or sets a JSON string containing a list of tags that are whitelisted for use by the push registration endpoint. | sdk/python/pulumi_azure_native/web/v20200901/web_app_site_push_settings_slot.py | tag_whitelist_json | pulumi-bot/pulumi-azure-native | python | @property
@pulumi.getter(name='tagWhitelistJson')
def tag_whitelist_json(self) -> pulumi.Output[Optional[str]]:
'\n \n '
return pulumi.get(self, 'tag_whitelist_json') |
@property
@pulumi.getter(name='tagsRequiringAuth')
def tags_requiring_auth(self) -> pulumi.Output[Optional[str]]:
"\n Gets or sets a JSON string containing a list of tags that require user authentication to be used in the push registration endpoint.\n Tags can consist of alphanumeric characters and the following:\n '_', '@', '#', '.', ':', '-'. \n Validation should be performed at the PushRequestHandler.\n "
return pulumi.get(self, 'tags_requiring_auth') | -2,422,842,160,071,476,000 | Gets or sets a JSON string containing a list of tags that require user authentication to be used in the push registration endpoint.
Tags can consist of alphanumeric characters and the following:
'_', '@', '#', '.', ':', '-'.
Validation should be performed at the PushRequestHandler. | sdk/python/pulumi_azure_native/web/v20200901/web_app_site_push_settings_slot.py | tags_requiring_auth | pulumi-bot/pulumi-azure-native | python | @property
@pulumi.getter(name='tagsRequiringAuth')
def tags_requiring_auth(self) -> pulumi.Output[Optional[str]]:
"\n Gets or sets a JSON string containing a list of tags that require user authentication to be used in the push registration endpoint.\n Tags can consist of alphanumeric characters and the following:\n '_', '@', '#', '.', ':', '-'. \n Validation should be performed at the PushRequestHandler.\n "
return pulumi.get(self, 'tags_requiring_auth') |
@property
@pulumi.getter
def type(self) -> pulumi.Output[str]:
'\n Resource type.\n '
return pulumi.get(self, 'type') | 2,132,950,812,122,862,800 | Resource type. | sdk/python/pulumi_azure_native/web/v20200901/web_app_site_push_settings_slot.py | type | pulumi-bot/pulumi-azure-native | python | @property
@pulumi.getter
def type(self) -> pulumi.Output[str]:
'\n \n '
return pulumi.get(self, 'type') |
def _define_structure(self):
'\n Define the main sizers building to build this application.\n '
self.main_sizer = wx.BoxSizer(wx.VERTICAL)
self.box_source = wx.StaticBox(self, (- 1), str('Kiessig Thickness Calculator'))
self.boxsizer_source = wx.StaticBoxSizer(self.box_source, wx.VERTICAL)
self.dq_name_sizer = wx.BoxSizer(wx.HORIZONTAL)
self.thickness_size_sizer = wx.BoxSizer(wx.HORIZONTAL)
self.hint_sizer = wx.BoxSizer(wx.HORIZONTAL)
self.button_sizer = wx.BoxSizer(wx.HORIZONTAL) | 4,143,718,605,268,381,000 | Define the main sizers building to build this application. | src/sas/sasgui/perspectives/calculator/kiessig_calculator_panel.py | _define_structure | andyfaff/sasview | python | def _define_structure(self):
'\n \n '
self.main_sizer = wx.BoxSizer(wx.VERTICAL)
self.box_source = wx.StaticBox(self, (- 1), str('Kiessig Thickness Calculator'))
self.boxsizer_source = wx.StaticBoxSizer(self.box_source, wx.VERTICAL)
self.dq_name_sizer = wx.BoxSizer(wx.HORIZONTAL)
self.thickness_size_sizer = wx.BoxSizer(wx.HORIZONTAL)
self.hint_sizer = wx.BoxSizer(wx.HORIZONTAL)
self.button_sizer = wx.BoxSizer(wx.HORIZONTAL) |
def _layout_dq_name(self):
'\n Fill the sizer containing dq name\n '
dq_value = str(self.kiessig.get_deltaq())
dq_unit_txt = wx.StaticText(self, (- 1), '[1/A]')
dq_name_txt = wx.StaticText(self, (- 1), 'Kiessig Fringe Width (Delta Q): ')
self.dq_name_tcl = InputTextCtrl(self, (- 1), size=(_BOX_WIDTH, (- 1)))
dq_hint = 'Type the Kiessig Fringe Width (Delta Q)'
self.dq_name_tcl.SetValue(dq_value)
self.dq_name_tcl.SetToolTipString(dq_hint)
id = wx.NewId()
self.compute_button = wx.Button(self, id, 'Compute')
hint_on_compute = 'Compute the diameter/thickness in the real space.'
self.compute_button.SetToolTipString(hint_on_compute)
self.Bind(wx.EVT_BUTTON, self.on_compute, id=id)
self.dq_name_sizer.AddMany([(dq_name_txt, 0, wx.LEFT, 15), (self.dq_name_tcl, 0, wx.LEFT, 15), (dq_unit_txt, 0, wx.LEFT, 10), (self.compute_button, 0, wx.LEFT, 30)]) | 1,429,371,075,089,788,000 | Fill the sizer containing dq name | src/sas/sasgui/perspectives/calculator/kiessig_calculator_panel.py | _layout_dq_name | andyfaff/sasview | python | def _layout_dq_name(self):
'\n \n '
dq_value = str(self.kiessig.get_deltaq())
dq_unit_txt = wx.StaticText(self, (- 1), '[1/A]')
dq_name_txt = wx.StaticText(self, (- 1), 'Kiessig Fringe Width (Delta Q): ')
self.dq_name_tcl = InputTextCtrl(self, (- 1), size=(_BOX_WIDTH, (- 1)))
dq_hint = 'Type the Kiessig Fringe Width (Delta Q)'
self.dq_name_tcl.SetValue(dq_value)
self.dq_name_tcl.SetToolTipString(dq_hint)
id = wx.NewId()
self.compute_button = wx.Button(self, id, 'Compute')
hint_on_compute = 'Compute the diameter/thickness in the real space.'
self.compute_button.SetToolTipString(hint_on_compute)
self.Bind(wx.EVT_BUTTON, self.on_compute, id=id)
self.dq_name_sizer.AddMany([(dq_name_txt, 0, wx.LEFT, 15), (self.dq_name_tcl, 0, wx.LEFT, 15), (dq_unit_txt, 0, wx.LEFT, 10), (self.compute_button, 0, wx.LEFT, 30)]) |
def _layout_thickness_size(self):
'\n Fill the sizer containing thickness information\n '
thick_unit = (('[' + self.kiessig.get_thickness_unit()) + ']')
thickness_size_txt = wx.StaticText(self, (- 1), 'Thickness (or Diameter): ')
self.thickness_size_tcl = OutputTextCtrl(self, (- 1), size=(_BOX_WIDTH, (- 1)))
thickness_size_hint = ' Estimated Size in Real Space'
self.thickness_size_tcl.SetToolTipString(thickness_size_hint)
thickness_size_unit_txt = wx.StaticText(self, (- 1), thick_unit)
self.thickness_size_sizer.AddMany([(thickness_size_txt, 0, wx.LEFT, 15), (self.thickness_size_tcl, 0, wx.LEFT, 15), (thickness_size_unit_txt, 0, wx.LEFT, 10)]) | 3,358,032,383,524,434,400 | Fill the sizer containing thickness information | src/sas/sasgui/perspectives/calculator/kiessig_calculator_panel.py | _layout_thickness_size | andyfaff/sasview | python | def _layout_thickness_size(self):
'\n \n '
thick_unit = (('[' + self.kiessig.get_thickness_unit()) + ']')
thickness_size_txt = wx.StaticText(self, (- 1), 'Thickness (or Diameter): ')
self.thickness_size_tcl = OutputTextCtrl(self, (- 1), size=(_BOX_WIDTH, (- 1)))
thickness_size_hint = ' Estimated Size in Real Space'
self.thickness_size_tcl.SetToolTipString(thickness_size_hint)
thickness_size_unit_txt = wx.StaticText(self, (- 1), thick_unit)
self.thickness_size_sizer.AddMany([(thickness_size_txt, 0, wx.LEFT, 15), (self.thickness_size_tcl, 0, wx.LEFT, 15), (thickness_size_unit_txt, 0, wx.LEFT, 10)]) |
def _layout_hint(self):
'\n Fill the sizer containing hint \n '
hint_msg = 'This tool is to approximately estimate '
hint_msg += 'the thickness of a layer'
hint_msg += ' or the diameter of particles\n '
hint_msg += 'from the Kiessig fringe width in SAS/NR data.'
hint_msg += ''
self.hint_txt = wx.StaticText(self, (- 1), hint_msg)
self.hint_sizer.AddMany([(self.hint_txt, 0, wx.LEFT, 15)]) | -8,116,110,328,013,586,000 | Fill the sizer containing hint | src/sas/sasgui/perspectives/calculator/kiessig_calculator_panel.py | _layout_hint | andyfaff/sasview | python | def _layout_hint(self):
'\n \n '
hint_msg = 'This tool is to approximately estimate '
hint_msg += 'the thickness of a layer'
hint_msg += ' or the diameter of particles\n '
hint_msg += 'from the Kiessig fringe width in SAS/NR data.'
hint_msg +=
self.hint_txt = wx.StaticText(self, (- 1), hint_msg)
self.hint_sizer.AddMany([(self.hint_txt, 0, wx.LEFT, 15)]) |
def _layout_button(self):
'\n Do the layout for the button widgets\n '
id = wx.NewId()
self.bt_help = wx.Button(self, id, 'HELP')
self.bt_help.Bind(wx.EVT_BUTTON, self.on_help)
self.bt_help.SetToolTipString('Help using the Kiessig fringe calculator.')
self.bt_close = wx.Button(self, wx.ID_CANCEL, 'Close')
self.bt_close.Bind(wx.EVT_BUTTON, self.on_close)
self.bt_close.SetToolTipString('Close this window.')
self.button_sizer.AddMany([(self.bt_help, 0, wx.LEFT, 260), (self.bt_close, 0, wx.LEFT, 20)]) | -6,821,566,193,316,706,000 | Do the layout for the button widgets | src/sas/sasgui/perspectives/calculator/kiessig_calculator_panel.py | _layout_button | andyfaff/sasview | python | def _layout_button(self):
'\n \n '
id = wx.NewId()
self.bt_help = wx.Button(self, id, 'HELP')
self.bt_help.Bind(wx.EVT_BUTTON, self.on_help)
self.bt_help.SetToolTipString('Help using the Kiessig fringe calculator.')
self.bt_close = wx.Button(self, wx.ID_CANCEL, 'Close')
self.bt_close.Bind(wx.EVT_BUTTON, self.on_close)
self.bt_close.SetToolTipString('Close this window.')
self.button_sizer.AddMany([(self.bt_help, 0, wx.LEFT, 260), (self.bt_close, 0, wx.LEFT, 20)]) |
def _do_layout(self):
'\n Draw window content\n '
self._define_structure()
self._layout_dq_name()
self._layout_thickness_size()
self._layout_hint()
self._layout_button()
self.boxsizer_source.AddMany([(self.dq_name_sizer, 0, ((wx.EXPAND | wx.TOP) | wx.BOTTOM), 5), (self.thickness_size_sizer, 0, ((wx.EXPAND | wx.TOP) | wx.BOTTOM), 5), (self.hint_sizer, 0, ((wx.EXPAND | wx.TOP) | wx.BOTTOM), 5)])
self.main_sizer.AddMany([(self.boxsizer_source, 0, wx.ALL, 10), (self.button_sizer, 0, ((wx.EXPAND | wx.TOP) | wx.BOTTOM), 5)])
self.SetSizer(self.main_sizer)
self.SetAutoLayout(True) | -3,224,533,211,146,210,300 | Draw window content | src/sas/sasgui/perspectives/calculator/kiessig_calculator_panel.py | _do_layout | andyfaff/sasview | python | def _do_layout(self):
'\n \n '
self._define_structure()
self._layout_dq_name()
self._layout_thickness_size()
self._layout_hint()
self._layout_button()
self.boxsizer_source.AddMany([(self.dq_name_sizer, 0, ((wx.EXPAND | wx.TOP) | wx.BOTTOM), 5), (self.thickness_size_sizer, 0, ((wx.EXPAND | wx.TOP) | wx.BOTTOM), 5), (self.hint_sizer, 0, ((wx.EXPAND | wx.TOP) | wx.BOTTOM), 5)])
self.main_sizer.AddMany([(self.boxsizer_source, 0, wx.ALL, 10), (self.button_sizer, 0, ((wx.EXPAND | wx.TOP) | wx.BOTTOM), 5)])
self.SetSizer(self.main_sizer)
self.SetAutoLayout(True) |
def on_help(self, event):
'\n Bring up the Kiessig fringe calculator Documentation whenever\n the HELP button is clicked.\n Calls DocumentationWindow with the path of the location within the\n documentation tree (after /doc/ ....". Note that when using old\n versions of Wx (before 2.9) and thus not the release version of\n installers, the help comes up at the top level of the file as\n webbrowser does not pass anything past the # to the browser when it is\n running "file:///...."\n\n :param evt: Triggers on clicking the help button\n '
_TreeLocation = 'user/sasgui/perspectives/calculator/'
_TreeLocation += 'kiessig_calculator_help.html'
_doc_viewer = DocumentationWindow(self, (- 1), _TreeLocation, '', 'Density/Volume Calculator Help') | 6,930,186,287,438,744,000 | Bring up the Kiessig fringe calculator Documentation whenever
the HELP button is clicked.
Calls DocumentationWindow with the path of the location within the
documentation tree (after /doc/ ....". Note that when using old
versions of Wx (before 2.9) and thus not the release version of
installers, the help comes up at the top level of the file as
webbrowser does not pass anything past the # to the browser when it is
running "file:///...."
:param evt: Triggers on clicking the help button | src/sas/sasgui/perspectives/calculator/kiessig_calculator_panel.py | on_help | andyfaff/sasview | python | def on_help(self, event):
'\n Bring up the Kiessig fringe calculator Documentation whenever\n the HELP button is clicked.\n Calls DocumentationWindow with the path of the location within the\n documentation tree (after /doc/ ....". Note that when using old\n versions of Wx (before 2.9) and thus not the release version of\n installers, the help comes up at the top level of the file as\n webbrowser does not pass anything past the # to the browser when it is\n running "file:///...."\n\n :param evt: Triggers on clicking the help button\n '
_TreeLocation = 'user/sasgui/perspectives/calculator/'
_TreeLocation += 'kiessig_calculator_help.html'
_doc_viewer = DocumentationWindow(self, (- 1), _TreeLocation, , 'Density/Volume Calculator Help') |
def on_close(self, event):
'\n close the window containing this panel\n '
self.parent.Close()
if (event is not None):
event.Skip() | -8,261,816,066,434,704,000 | close the window containing this panel | src/sas/sasgui/perspectives/calculator/kiessig_calculator_panel.py | on_close | andyfaff/sasview | python | def on_close(self, event):
'\n \n '
self.parent.Close()
if (event is not None):
event.Skip() |
def on_compute(self, event):
'\n Execute the computation of thickness\n '
if (event is not None):
event.Skip()
dq = self.dq_name_tcl.GetValue()
self.kiessig.set_deltaq(dq)
output = self.kiessig.compute_thickness()
thickness = self.format_number(output)
self.thickness_size_tcl.SetValue(str(thickness)) | 4,238,333,682,032,974,300 | Execute the computation of thickness | src/sas/sasgui/perspectives/calculator/kiessig_calculator_panel.py | on_compute | andyfaff/sasview | python | def on_compute(self, event):
'\n \n '
if (event is not None):
event.Skip()
dq = self.dq_name_tcl.GetValue()
self.kiessig.set_deltaq(dq)
output = self.kiessig.compute_thickness()
thickness = self.format_number(output)
self.thickness_size_tcl.SetValue(str(thickness)) |
def format_number(self, value=None):
'\n Return a float in a standardized, human-readable formatted string\n '
try:
value = float(value)
except:
output = None
return output
output = ('%-7.4g' % value)
return output.lstrip().rstrip() | 3,595,117,808,034,005,000 | Return a float in a standardized, human-readable formatted string | src/sas/sasgui/perspectives/calculator/kiessig_calculator_panel.py | format_number | andyfaff/sasview | python | def format_number(self, value=None):
'\n \n '
try:
value = float(value)
except:
output = None
return output
output = ('%-7.4g' % value)
return output.lstrip().rstrip() |
def _onparamEnter(self, event=None):
'\n On Text_enter_callback, perform compute\n '
self.on_compute(event) | -6,448,870,365,049,814,000 | On Text_enter_callback, perform compute | src/sas/sasgui/perspectives/calculator/kiessig_calculator_panel.py | _onparamEnter | andyfaff/sasview | python | def _onparamEnter(self, event=None):
'\n \n '
self.on_compute(event) |
def on_close(self, event):
'\n Close event\n '
if (self.manager is not None):
self.manager.kiessig_frame = None
self.Destroy() | -8,310,142,565,720,282,000 | Close event | src/sas/sasgui/perspectives/calculator/kiessig_calculator_panel.py | on_close | andyfaff/sasview | python | def on_close(self, event):
'\n \n '
if (self.manager is not None):
self.manager.kiessig_frame = None
self.Destroy() |
@classmethod
def find_project_root_directory(cls, current_directory: Optional[Path]) -> Optional[Path]:
"\n Given a directory (with ``None`` implying the current directory) assumed to be at or under this project's root,\n find the project root directory.\n This implementation attempts to find a directory having both a ``.git/`` child directory and a ``.env`` file.\n Parameters\n ----------\n current_directory\n Returns\n -------\n Optional[Path]\n The project root directory, or ``None`` if it fails to find it.\n "
if (not current_directory):
current_directory = TestGetGithub._current_dir
abs_root = Path(current_directory.absolute().root)
while (current_directory.absolute() != abs_root):
if (not current_directory.is_dir()):
current_directory = current_directory.parent
continue
git_sub_dir = current_directory.joinpath('.git')
child_env_file = current_directory.joinpath('config.yaml')
if (git_sub_dir.exists() and git_sub_dir.is_dir() and child_env_file.exists() and child_env_file.is_file()):
return current_directory
current_directory = current_directory.parent
return None | -2,530,477,784,102,690,000 | Given a directory (with ``None`` implying the current directory) assumed to be at or under this project's root,
find the project root directory.
This implementation attempts to find a directory having both a ``.git/`` child directory and a ``.env`` file.
Parameters
----------
current_directory
Returns
-------
Optional[Path]
The project root directory, or ``None`` if it fails to find it. | github_archive/test/test_get_github.py | find_project_root_directory | hellkite500/github_archive | python | @classmethod
def find_project_root_directory(cls, current_directory: Optional[Path]) -> Optional[Path]:
"\n Given a directory (with ``None`` implying the current directory) assumed to be at or under this project's root,\n find the project root directory.\n This implementation attempts to find a directory having both a ``.git/`` child directory and a ``.env`` file.\n Parameters\n ----------\n current_directory\n Returns\n -------\n Optional[Path]\n The project root directory, or ``None`` if it fails to find it.\n "
if (not current_directory):
current_directory = TestGetGithub._current_dir
abs_root = Path(current_directory.absolute().root)
while (current_directory.absolute() != abs_root):
if (not current_directory.is_dir()):
current_directory = current_directory.parent
continue
git_sub_dir = current_directory.joinpath('.git')
child_env_file = current_directory.joinpath('config.yaml')
if (git_sub_dir.exists() and git_sub_dir.is_dir() and child_env_file.exists() and child_env_file.is_file()):
return current_directory
current_directory = current_directory.parent
return None |
@classmethod
def load_token(cls):
"\n Read an API token from a configuration file, if none found, use '' for no auth\n "
token = ''
root_dir = cls.find_project_root_directory(None)
if (not root_dir):
return token
config_file = (root_dir / 'config.yaml')
if config_file.exists():
with open(config_file) as file:
config = yaml.load(file, Loader=yaml.FullLoader)
try:
token = config['token']
except:
print('Unable to load api-token from project root directory config.yaml')
return token | 7,484,951,432,618,107,000 | Read an API token from a configuration file, if none found, use '' for no auth | github_archive/test/test_get_github.py | load_token | hellkite500/github_archive | python | @classmethod
def load_token(cls):
"\n \n "
token =
root_dir = cls.find_project_root_directory(None)
if (not root_dir):
return token
config_file = (root_dir / 'config.yaml')
if config_file.exists():
with open(config_file) as file:
config = yaml.load(file, Loader=yaml.FullLoader)
try:
token = config['token']
except:
print('Unable to load api-token from project root directory config.yaml')
return token |
def test_get_repo_meta(self):
'\n Test the archive_repo function to ensure all meta data is properly captured\n '
meta = get_repo_meta(self.repo, self.time, TestGetGithub._current_dir)
self.assertIsNotNone(meta)
self.assertTrue(len(meta), 6)
pattern = '{repo}_{name}_{time}.json'.format(repo=self.repo_string, name='{name}', time=self.time)
self.assertEqual(meta[0].name, pattern.format(name='comments'))
self.assertEqual(meta[1].name, pattern.format(name='issues'))
self.assertEqual(meta[2].name, pattern.format(name='issue_comments'))
self.assertEqual(meta[3].name, pattern.format(name='pulls'))
self.assertEqual(meta[4].name, pattern.format(name='pulls_comments'))
self.assertEqual(meta[5].name, pattern.format(name='pulls_review_comments'))
self.assertTrue((TestGetGithub._current_dir / pattern.format(name='comments')).exists())
self.assertTrue((TestGetGithub._current_dir / pattern.format(name='issues')).exists())
self.assertTrue((TestGetGithub._current_dir / pattern.format(name='issue_comments')).exists())
self.assertTrue((TestGetGithub._current_dir / pattern.format(name='pulls')).exists())
self.assertTrue((TestGetGithub._current_dir / pattern.format(name='pulls_comments')).exists())
self.assertTrue((TestGetGithub._current_dir / pattern.format(name='pulls_review_comments')).exists()) | 8,121,341,174,717,497,000 | Test the archive_repo function to ensure all meta data is properly captured | github_archive/test/test_get_github.py | test_get_repo_meta | hellkite500/github_archive | python | def test_get_repo_meta(self):
'\n \n '
meta = get_repo_meta(self.repo, self.time, TestGetGithub._current_dir)
self.assertIsNotNone(meta)
self.assertTrue(len(meta), 6)
pattern = '{repo}_{name}_{time}.json'.format(repo=self.repo_string, name='{name}', time=self.time)
self.assertEqual(meta[0].name, pattern.format(name='comments'))
self.assertEqual(meta[1].name, pattern.format(name='issues'))
self.assertEqual(meta[2].name, pattern.format(name='issue_comments'))
self.assertEqual(meta[3].name, pattern.format(name='pulls'))
self.assertEqual(meta[4].name, pattern.format(name='pulls_comments'))
self.assertEqual(meta[5].name, pattern.format(name='pulls_review_comments'))
self.assertTrue((TestGetGithub._current_dir / pattern.format(name='comments')).exists())
self.assertTrue((TestGetGithub._current_dir / pattern.format(name='issues')).exists())
self.assertTrue((TestGetGithub._current_dir / pattern.format(name='issue_comments')).exists())
self.assertTrue((TestGetGithub._current_dir / pattern.format(name='pulls')).exists())
self.assertTrue((TestGetGithub._current_dir / pattern.format(name='pulls_comments')).exists())
self.assertTrue((TestGetGithub._current_dir / pattern.format(name='pulls_review_comments')).exists()) |
def test_clone_and_archive(self):
'\n Test the clone functionality\n '
self.assertFalse(self.repo.has_wiki)
clone_url = self.repo.clone_url
archive_name = clone_and_archive(self.repo_string, clone_url, self.time, TestGetGithub._current_dir, [])
name = '{repo}_github_archive_{time}.tar.gz'.format(repo=self.repo_string, time=self.time)
self.assertEqual(archive_name.name, name)
self.assertTrue((TestGetGithub._current_dir / name).exists()) | -257,225,097,966,887,840 | Test the clone functionality | github_archive/test/test_get_github.py | test_clone_and_archive | hellkite500/github_archive | python | def test_clone_and_archive(self):
'\n \n '
self.assertFalse(self.repo.has_wiki)
clone_url = self.repo.clone_url
archive_name = clone_and_archive(self.repo_string, clone_url, self.time, TestGetGithub._current_dir, [])
name = '{repo}_github_archive_{time}.tar.gz'.format(repo=self.repo_string, time=self.time)
self.assertEqual(archive_name.name, name)
self.assertTrue((TestGetGithub._current_dir / name).exists()) |
def test_clone_and_archive_1(self):
'\n Test cloning a repo with a wiki\n '
self.assertTrue(self.wiki_repo.has_wiki)
wiki_url = (self.wiki_repo.clone_url[:(- 3)] + 'wiki.git')
clone_url = self.wiki_repo.clone_url
archive_name = clone_and_archive(self.repo_w_wiki, clone_url, self.time, TestGetGithub._current_dir, [], wiki_url)
name = '{repo}_github_archive_{time}.tar.gz'.format(repo=self.repo_w_wiki, time=self.time)
self.assertEqual(archive_name.name, name)
self.assertTrue((TestGetGithub._current_dir / name).exists()) | -7,822,465,264,797,826,000 | Test cloning a repo with a wiki | github_archive/test/test_get_github.py | test_clone_and_archive_1 | hellkite500/github_archive | python | def test_clone_and_archive_1(self):
'\n \n '
self.assertTrue(self.wiki_repo.has_wiki)
wiki_url = (self.wiki_repo.clone_url[:(- 3)] + 'wiki.git')
clone_url = self.wiki_repo.clone_url
archive_name = clone_and_archive(self.repo_w_wiki, clone_url, self.time, TestGetGithub._current_dir, [], wiki_url)
name = '{repo}_github_archive_{time}.tar.gz'.format(repo=self.repo_w_wiki, time=self.time)
self.assertEqual(archive_name.name, name)
self.assertTrue((TestGetGithub._current_dir / name).exists()) |
def policy_v0():
'Autoaugment policy that was used in AutoAugment Detection Paper.'
policy = [[('TranslateX_BBox', 0.6, 4), ('Equalize', 0.8, 10)], [('TranslateY_Only_BBoxes', 0.2, 2), ('Cutout', 0.8, 8)], [('Sharpness', 0.0, 8), ('ShearX_BBox', 0.4, 0)], [('ShearY_BBox', 1.0, 2), ('TranslateY_Only_BBoxes', 0.6, 6)], [('Rotate_BBox', 0.6, 10), ('Color', 1.0, 6)]]
return policy | 8,460,943,867,710,150,000 | Autoaugment policy that was used in AutoAugment Detection Paper. | efficientdet/aug/autoaugment.py | policy_v0 | datawowio/automl | python | def policy_v0():
policy = [[('TranslateX_BBox', 0.6, 4), ('Equalize', 0.8, 10)], [('TranslateY_Only_BBoxes', 0.2, 2), ('Cutout', 0.8, 8)], [('Sharpness', 0.0, 8), ('ShearX_BBox', 0.4, 0)], [('ShearY_BBox', 1.0, 2), ('TranslateY_Only_BBoxes', 0.6, 6)], [('Rotate_BBox', 0.6, 10), ('Color', 1.0, 6)]]
return policy |
def policy_v1():
'Autoaugment policy that was used in AutoAugment Detection Paper.'
policy = [[('TranslateX_BBox', 0.6, 4), ('Equalize', 0.8, 10)], [('TranslateY_Only_BBoxes', 0.2, 2), ('Cutout', 0.8, 8)], [('Sharpness', 0.0, 8), ('ShearX_BBox', 0.4, 0)], [('ShearY_BBox', 1.0, 2), ('TranslateY_Only_BBoxes', 0.6, 6)], [('Rotate_BBox', 0.6, 10), ('Color', 1.0, 6)], [('Color', 0.0, 0), ('ShearX_Only_BBoxes', 0.8, 4)], [('ShearY_Only_BBoxes', 0.8, 2), ('Flip_Only_BBoxes', 0.0, 10)], [('Equalize', 0.6, 10), ('TranslateX_BBox', 0.2, 2)], [('Color', 1.0, 10), ('TranslateY_Only_BBoxes', 0.4, 6)], [('Rotate_BBox', 0.8, 10), ('Contrast', 0.0, 10)], [('Cutout', 0.2, 2), ('Brightness', 0.8, 10)], [('Color', 1.0, 6), ('Equalize', 1.0, 2)], [('Cutout_Only_BBoxes', 0.4, 6), ('TranslateY_Only_BBoxes', 0.8, 2)], [('Color', 0.2, 8), ('Rotate_BBox', 0.8, 10)], [('Sharpness', 0.4, 4), ('TranslateY_Only_BBoxes', 0.0, 4)], [('Sharpness', 1.0, 4), ('SolarizeAdd', 0.4, 4)], [('Rotate_BBox', 1.0, 8), ('Sharpness', 0.2, 8)], [('ShearY_BBox', 0.6, 10), ('Equalize_Only_BBoxes', 0.6, 8)], [('ShearX_BBox', 0.2, 6), ('TranslateY_Only_BBoxes', 0.2, 10)], [('SolarizeAdd', 0.6, 8), ('Brightness', 0.8, 10)]]
return policy | -8,715,538,783,788,513,000 | Autoaugment policy that was used in AutoAugment Detection Paper. | efficientdet/aug/autoaugment.py | policy_v1 | datawowio/automl | python | def policy_v1():
policy = [[('TranslateX_BBox', 0.6, 4), ('Equalize', 0.8, 10)], [('TranslateY_Only_BBoxes', 0.2, 2), ('Cutout', 0.8, 8)], [('Sharpness', 0.0, 8), ('ShearX_BBox', 0.4, 0)], [('ShearY_BBox', 1.0, 2), ('TranslateY_Only_BBoxes', 0.6, 6)], [('Rotate_BBox', 0.6, 10), ('Color', 1.0, 6)], [('Color', 0.0, 0), ('ShearX_Only_BBoxes', 0.8, 4)], [('ShearY_Only_BBoxes', 0.8, 2), ('Flip_Only_BBoxes', 0.0, 10)], [('Equalize', 0.6, 10), ('TranslateX_BBox', 0.2, 2)], [('Color', 1.0, 10), ('TranslateY_Only_BBoxes', 0.4, 6)], [('Rotate_BBox', 0.8, 10), ('Contrast', 0.0, 10)], [('Cutout', 0.2, 2), ('Brightness', 0.8, 10)], [('Color', 1.0, 6), ('Equalize', 1.0, 2)], [('Cutout_Only_BBoxes', 0.4, 6), ('TranslateY_Only_BBoxes', 0.8, 2)], [('Color', 0.2, 8), ('Rotate_BBox', 0.8, 10)], [('Sharpness', 0.4, 4), ('TranslateY_Only_BBoxes', 0.0, 4)], [('Sharpness', 1.0, 4), ('SolarizeAdd', 0.4, 4)], [('Rotate_BBox', 1.0, 8), ('Sharpness', 0.2, 8)], [('ShearY_BBox', 0.6, 10), ('Equalize_Only_BBoxes', 0.6, 8)], [('ShearX_BBox', 0.2, 6), ('TranslateY_Only_BBoxes', 0.2, 10)], [('SolarizeAdd', 0.6, 8), ('Brightness', 0.8, 10)]]
return policy |
def policy_vtest():
'Autoaugment test policy for debugging.'
policy = [[('TranslateX_BBox', 1.0, 4), ('Equalize', 1.0, 10)]]
return policy | -9,018,532,416,153,881,000 | Autoaugment test policy for debugging. | efficientdet/aug/autoaugment.py | policy_vtest | datawowio/automl | python | def policy_vtest():
policy = [[('TranslateX_BBox', 1.0, 4), ('Equalize', 1.0, 10)]]
return policy |
def policy_v2():
'Additional policy that performs well on object detection.'
policy = [[('Color', 0.0, 6), ('Cutout', 0.6, 8), ('Sharpness', 0.4, 8)], [('Rotate_BBox', 0.4, 8), ('Sharpness', 0.4, 2), ('Rotate_BBox', 0.8, 10)], [('TranslateY_BBox', 1.0, 8), ('AutoContrast', 0.8, 2)], [('AutoContrast', 0.4, 6), ('ShearX_BBox', 0.8, 8), ('Brightness', 0.0, 10)], [('SolarizeAdd', 0.2, 6), ('Contrast', 0.0, 10), ('AutoContrast', 0.6, 0)], [('Cutout', 0.2, 0), ('Solarize', 0.8, 8), ('Color', 1.0, 4)], [('TranslateY_BBox', 0.0, 4), ('Equalize', 0.6, 8), ('Solarize', 0.0, 10)], [('TranslateY_BBox', 0.2, 2), ('ShearY_BBox', 0.8, 8), ('Rotate_BBox', 0.8, 8)], [('Cutout', 0.8, 8), ('Brightness', 0.8, 8), ('Cutout', 0.2, 2)], [('Color', 0.8, 4), ('TranslateY_BBox', 1.0, 6), ('Rotate_BBox', 0.6, 6)], [('Rotate_BBox', 0.6, 10), ('BBox_Cutout', 1.0, 4), ('Cutout', 0.2, 8)], [('Rotate_BBox', 0.0, 0), ('Equalize', 0.6, 6), ('ShearY_BBox', 0.6, 8)], [('Brightness', 0.8, 8), ('AutoContrast', 0.4, 2), ('Brightness', 0.2, 2)], [('TranslateY_BBox', 0.4, 8), ('Solarize', 0.4, 6), ('SolarizeAdd', 0.2, 10)], [('Contrast', 1.0, 10), ('SolarizeAdd', 0.2, 8), ('Equalize', 0.2, 4)]]
return policy | 8,499,406,954,455,301,000 | Additional policy that performs well on object detection. | efficientdet/aug/autoaugment.py | policy_v2 | datawowio/automl | python | def policy_v2():
policy = [[('Color', 0.0, 6), ('Cutout', 0.6, 8), ('Sharpness', 0.4, 8)], [('Rotate_BBox', 0.4, 8), ('Sharpness', 0.4, 2), ('Rotate_BBox', 0.8, 10)], [('TranslateY_BBox', 1.0, 8), ('AutoContrast', 0.8, 2)], [('AutoContrast', 0.4, 6), ('ShearX_BBox', 0.8, 8), ('Brightness', 0.0, 10)], [('SolarizeAdd', 0.2, 6), ('Contrast', 0.0, 10), ('AutoContrast', 0.6, 0)], [('Cutout', 0.2, 0), ('Solarize', 0.8, 8), ('Color', 1.0, 4)], [('TranslateY_BBox', 0.0, 4), ('Equalize', 0.6, 8), ('Solarize', 0.0, 10)], [('TranslateY_BBox', 0.2, 2), ('ShearY_BBox', 0.8, 8), ('Rotate_BBox', 0.8, 8)], [('Cutout', 0.8, 8), ('Brightness', 0.8, 8), ('Cutout', 0.2, 2)], [('Color', 0.8, 4), ('TranslateY_BBox', 1.0, 6), ('Rotate_BBox', 0.6, 6)], [('Rotate_BBox', 0.6, 10), ('BBox_Cutout', 1.0, 4), ('Cutout', 0.2, 8)], [('Rotate_BBox', 0.0, 0), ('Equalize', 0.6, 6), ('ShearY_BBox', 0.6, 8)], [('Brightness', 0.8, 8), ('AutoContrast', 0.4, 2), ('Brightness', 0.2, 2)], [('TranslateY_BBox', 0.4, 8), ('Solarize', 0.4, 6), ('SolarizeAdd', 0.2, 10)], [('Contrast', 1.0, 10), ('SolarizeAdd', 0.2, 8), ('Equalize', 0.2, 4)]]
return policy |
def policy_v3():
'"Additional policy that performs well on object detection.'
policy = [[('Posterize', 0.8, 2), ('TranslateX_BBox', 1.0, 8)], [('BBox_Cutout', 0.2, 10), ('Sharpness', 1.0, 8)], [('Rotate_BBox', 0.6, 8), ('Rotate_BBox', 0.8, 10)], [('Equalize', 0.8, 10), ('AutoContrast', 0.2, 10)], [('SolarizeAdd', 0.2, 2), ('TranslateY_BBox', 0.2, 8)], [('Sharpness', 0.0, 2), ('Color', 0.4, 8)], [('Equalize', 1.0, 8), ('TranslateY_BBox', 1.0, 8)], [('Posterize', 0.6, 2), ('Rotate_BBox', 0.0, 10)], [('AutoContrast', 0.6, 0), ('Rotate_BBox', 1.0, 6)], [('Brightness', 1.0, 2), ('TranslateY_BBox', 1.0, 6)], [('Contrast', 0.0, 2), ('ShearY_BBox', 0.8, 0)], [('AutoContrast', 0.8, 10), ('Contrast', 0.2, 10)], [('SolarizeAdd', 0.8, 6), ('Equalize', 0.8, 8)]]
return policy | -2,631,217,006,608,270,000 | "Additional policy that performs well on object detection. | efficientdet/aug/autoaugment.py | policy_v3 | datawowio/automl | python | def policy_v3():
policy = [[('Posterize', 0.8, 2), ('TranslateX_BBox', 1.0, 8)], [('BBox_Cutout', 0.2, 10), ('Sharpness', 1.0, 8)], [('Rotate_BBox', 0.6, 8), ('Rotate_BBox', 0.8, 10)], [('Equalize', 0.8, 10), ('AutoContrast', 0.2, 10)], [('SolarizeAdd', 0.2, 2), ('TranslateY_BBox', 0.2, 8)], [('Sharpness', 0.0, 2), ('Color', 0.4, 8)], [('Equalize', 1.0, 8), ('TranslateY_BBox', 1.0, 8)], [('Posterize', 0.6, 2), ('Rotate_BBox', 0.0, 10)], [('AutoContrast', 0.6, 0), ('Rotate_BBox', 1.0, 6)], [('Brightness', 1.0, 2), ('TranslateY_BBox', 1.0, 6)], [('Contrast', 0.0, 2), ('ShearY_BBox', 0.8, 0)], [('AutoContrast', 0.8, 10), ('Contrast', 0.2, 10)], [('SolarizeAdd', 0.8, 6), ('Equalize', 0.8, 8)]]
return policy |
def blend(image1, image2, factor):
'Blend image1 and image2 using \'factor\'.\n\n Factor can be above 0.0. A value of 0.0 means only image1 is used.\n A value of 1.0 means only image2 is used. A value between 0.0 and\n 1.0 means we linearly interpolate the pixel values between the two\n images. A value greater than 1.0 "extrapolates" the difference\n between the two pixel values, and we clip the results to values\n between 0 and 255.\n\n Args:\n image1: An image Tensor of type uint8.\n image2: An image Tensor of type uint8.\n factor: A floating point value above 0.0.\n\n Returns:\n A blended image Tensor of type uint8.\n '
if (factor == 0.0):
return tf.convert_to_tensor(image1)
if (factor == 1.0):
return tf.convert_to_tensor(image2)
image1 = tf.to_float(image1)
image2 = tf.to_float(image2)
difference = (image2 - image1)
scaled = (factor * difference)
temp = (tf.to_float(image1) + scaled)
if ((factor > 0.0) and (factor < 1.0)):
return tf.cast(temp, tf.uint8)
return tf.cast(tf.clip_by_value(temp, 0.0, 255.0), tf.uint8) | -7,071,893,540,884,844,000 | Blend image1 and image2 using 'factor'.
Factor can be above 0.0. A value of 0.0 means only image1 is used.
A value of 1.0 means only image2 is used. A value between 0.0 and
1.0 means we linearly interpolate the pixel values between the two
images. A value greater than 1.0 "extrapolates" the difference
between the two pixel values, and we clip the results to values
between 0 and 255.
Args:
image1: An image Tensor of type uint8.
image2: An image Tensor of type uint8.
factor: A floating point value above 0.0.
Returns:
A blended image Tensor of type uint8. | efficientdet/aug/autoaugment.py | blend | datawowio/automl | python | def blend(image1, image2, factor):
'Blend image1 and image2 using \'factor\'.\n\n Factor can be above 0.0. A value of 0.0 means only image1 is used.\n A value of 1.0 means only image2 is used. A value between 0.0 and\n 1.0 means we linearly interpolate the pixel values between the two\n images. A value greater than 1.0 "extrapolates" the difference\n between the two pixel values, and we clip the results to values\n between 0 and 255.\n\n Args:\n image1: An image Tensor of type uint8.\n image2: An image Tensor of type uint8.\n factor: A floating point value above 0.0.\n\n Returns:\n A blended image Tensor of type uint8.\n '
if (factor == 0.0):
return tf.convert_to_tensor(image1)
if (factor == 1.0):
return tf.convert_to_tensor(image2)
image1 = tf.to_float(image1)
image2 = tf.to_float(image2)
difference = (image2 - image1)
scaled = (factor * difference)
temp = (tf.to_float(image1) + scaled)
if ((factor > 0.0) and (factor < 1.0)):
return tf.cast(temp, tf.uint8)
return tf.cast(tf.clip_by_value(temp, 0.0, 255.0), tf.uint8) |
def cutout(image, pad_size, replace=0):
'Apply cutout (https://arxiv.org/abs/1708.04552) to image.\n\n This operation applies a (2*pad_size x 2*pad_size) mask of zeros to\n a random location within `img`. The pixel values filled in will be of the\n value `replace`. The located where the mask will be applied is randomly\n chosen uniformly over the whole image.\n\n Args:\n image: An image Tensor of type uint8.\n pad_size: Specifies how big the zero mask that will be generated is that\n is applied to the image. The mask will be of size\n (2*pad_size x 2*pad_size).\n replace: What pixel value to fill in the image in the area that has\n the cutout mask applied to it.\n\n Returns:\n An image Tensor that is of type uint8.\n '
image_height = tf.maximum(tf.shape(image)[0], 10)
image_width = tf.maximum(tf.shape(image)[1], 10)
cutout_center_height = tf.random_uniform(shape=[], minval=0, maxval=image_height, dtype=tf.int32)
cutout_center_width = tf.random_uniform(shape=[], minval=0, maxval=image_width, dtype=tf.int32)
lower_pad = tf.maximum(0, (cutout_center_height - pad_size))
upper_pad = tf.maximum(0, ((image_height - cutout_center_height) - pad_size))
left_pad = tf.maximum(0, (cutout_center_width - pad_size))
right_pad = tf.maximum(0, ((image_width - cutout_center_width) - pad_size))
cutout_shape = [(image_height - (lower_pad + upper_pad)), (image_width - (left_pad + right_pad))]
padding_dims = [[lower_pad, upper_pad], [left_pad, right_pad]]
mask = tf.pad(tf.zeros(cutout_shape, dtype=image.dtype), padding_dims, constant_values=1)
mask = tf.expand_dims(mask, (- 1))
mask = tf.tile(mask, [1, 1, 3])
image = tf.where(tf.equal(mask, 0), (tf.ones_like(image, dtype=image.dtype) * replace), image)
return image | -4,239,343,247,505,422,000 | Apply cutout (https://arxiv.org/abs/1708.04552) to image.
This operation applies a (2*pad_size x 2*pad_size) mask of zeros to
a random location within `img`. The pixel values filled in will be of the
value `replace`. The located where the mask will be applied is randomly
chosen uniformly over the whole image.
Args:
image: An image Tensor of type uint8.
pad_size: Specifies how big the zero mask that will be generated is that
is applied to the image. The mask will be of size
(2*pad_size x 2*pad_size).
replace: What pixel value to fill in the image in the area that has
the cutout mask applied to it.
Returns:
An image Tensor that is of type uint8. | efficientdet/aug/autoaugment.py | cutout | datawowio/automl | python | def cutout(image, pad_size, replace=0):
'Apply cutout (https://arxiv.org/abs/1708.04552) to image.\n\n This operation applies a (2*pad_size x 2*pad_size) mask of zeros to\n a random location within `img`. The pixel values filled in will be of the\n value `replace`. The located where the mask will be applied is randomly\n chosen uniformly over the whole image.\n\n Args:\n image: An image Tensor of type uint8.\n pad_size: Specifies how big the zero mask that will be generated is that\n is applied to the image. The mask will be of size\n (2*pad_size x 2*pad_size).\n replace: What pixel value to fill in the image in the area that has\n the cutout mask applied to it.\n\n Returns:\n An image Tensor that is of type uint8.\n '
image_height = tf.maximum(tf.shape(image)[0], 10)
image_width = tf.maximum(tf.shape(image)[1], 10)
cutout_center_height = tf.random_uniform(shape=[], minval=0, maxval=image_height, dtype=tf.int32)
cutout_center_width = tf.random_uniform(shape=[], minval=0, maxval=image_width, dtype=tf.int32)
lower_pad = tf.maximum(0, (cutout_center_height - pad_size))
upper_pad = tf.maximum(0, ((image_height - cutout_center_height) - pad_size))
left_pad = tf.maximum(0, (cutout_center_width - pad_size))
right_pad = tf.maximum(0, ((image_width - cutout_center_width) - pad_size))
cutout_shape = [(image_height - (lower_pad + upper_pad)), (image_width - (left_pad + right_pad))]
padding_dims = [[lower_pad, upper_pad], [left_pad, right_pad]]
mask = tf.pad(tf.zeros(cutout_shape, dtype=image.dtype), padding_dims, constant_values=1)
mask = tf.expand_dims(mask, (- 1))
mask = tf.tile(mask, [1, 1, 3])
image = tf.where(tf.equal(mask, 0), (tf.ones_like(image, dtype=image.dtype) * replace), image)
return image |
def color(image, factor):
'Equivalent of PIL Color.'
degenerate = tf.image.grayscale_to_rgb(tf.image.rgb_to_grayscale(image))
return blend(degenerate, image, factor) | 2,872,861,326,192,433,000 | Equivalent of PIL Color. | efficientdet/aug/autoaugment.py | color | datawowio/automl | python | def color(image, factor):
degenerate = tf.image.grayscale_to_rgb(tf.image.rgb_to_grayscale(image))
return blend(degenerate, image, factor) |
def contrast(image, factor):
'Equivalent of PIL Contrast.'
degenerate = tf.image.rgb_to_grayscale(image)
degenerate = tf.cast(degenerate, tf.int32)
mean = tf.reduce_mean(tf.cast(degenerate, tf.float32))
degenerate = (tf.ones_like(degenerate, dtype=tf.float32) * mean)
degenerate = tf.clip_by_value(degenerate, 0.0, 255.0)
degenerate = tf.image.grayscale_to_rgb(tf.cast(degenerate, tf.uint8))
return blend(degenerate, image, factor) | 3,150,907,722,058,286,000 | Equivalent of PIL Contrast. | efficientdet/aug/autoaugment.py | contrast | datawowio/automl | python | def contrast(image, factor):
degenerate = tf.image.rgb_to_grayscale(image)
degenerate = tf.cast(degenerate, tf.int32)
mean = tf.reduce_mean(tf.cast(degenerate, tf.float32))
degenerate = (tf.ones_like(degenerate, dtype=tf.float32) * mean)
degenerate = tf.clip_by_value(degenerate, 0.0, 255.0)
degenerate = tf.image.grayscale_to_rgb(tf.cast(degenerate, tf.uint8))
return blend(degenerate, image, factor) |
def brightness(image, factor):
'Equivalent of PIL Brightness.'
degenerate = tf.zeros_like(image)
return blend(degenerate, image, factor) | -5,514,793,971,791,669,000 | Equivalent of PIL Brightness. | efficientdet/aug/autoaugment.py | brightness | datawowio/automl | python | def brightness(image, factor):
degenerate = tf.zeros_like(image)
return blend(degenerate, image, factor) |
def posterize(image, bits):
'Equivalent of PIL Posterize.'
shift = (8 - bits)
return tf.bitwise.left_shift(tf.bitwise.right_shift(image, shift), shift) | -7,653,707,230,299,955,000 | Equivalent of PIL Posterize. | efficientdet/aug/autoaugment.py | posterize | datawowio/automl | python | def posterize(image, bits):
shift = (8 - bits)
return tf.bitwise.left_shift(tf.bitwise.right_shift(image, shift), shift) |
def rotate(image, degrees, replace):
'Rotates the image by degrees either clockwise or counterclockwise.\n\n Args:\n image: An image Tensor of type uint8.\n degrees: Float, a scalar angle in degrees to rotate all images by. If\n degrees is positive the image will be rotated clockwise otherwise it will\n be rotated counterclockwise.\n replace: A one or three value 1D tensor to fill empty pixels caused by\n the rotate operation.\n\n Returns:\n The rotated version of image.\n '
degrees_to_radians = (math.pi / 180.0)
radians = (degrees * degrees_to_radians)
image = image_ops.rotate(wrap(image), radians)
return unwrap(image, replace) | 9,033,878,547,422,465,000 | Rotates the image by degrees either clockwise or counterclockwise.
Args:
image: An image Tensor of type uint8.
degrees: Float, a scalar angle in degrees to rotate all images by. If
degrees is positive the image will be rotated clockwise otherwise it will
be rotated counterclockwise.
replace: A one or three value 1D tensor to fill empty pixels caused by
the rotate operation.
Returns:
The rotated version of image. | efficientdet/aug/autoaugment.py | rotate | datawowio/automl | python | def rotate(image, degrees, replace):
'Rotates the image by degrees either clockwise or counterclockwise.\n\n Args:\n image: An image Tensor of type uint8.\n degrees: Float, a scalar angle in degrees to rotate all images by. If\n degrees is positive the image will be rotated clockwise otherwise it will\n be rotated counterclockwise.\n replace: A one or three value 1D tensor to fill empty pixels caused by\n the rotate operation.\n\n Returns:\n The rotated version of image.\n '
degrees_to_radians = (math.pi / 180.0)
radians = (degrees * degrees_to_radians)
image = image_ops.rotate(wrap(image), radians)
return unwrap(image, replace) |
def random_shift_bbox(image, bbox, pixel_scaling, replace, new_min_bbox_coords=None):
'Move the bbox and the image content to a slightly new random location.\n\n Args:\n image: 3D uint8 Tensor.\n bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)\n of type float that represents the normalized coordinates between 0 and 1.\n The potential values for the new min corner of the bbox will be between\n [old_min - pixel_scaling * bbox_height/2,\n old_min - pixel_scaling * bbox_height/2].\n pixel_scaling: A float between 0 and 1 that specifies the pixel range\n that the new bbox location will be sampled from.\n replace: A one or three value 1D tensor to fill empty pixels.\n new_min_bbox_coords: If not None, then this is a tuple that specifies the\n (min_y, min_x) coordinates of the new bbox. Normally this is randomly\n specified, but this allows it to be manually set. The coordinates are\n the absolute coordinates between 0 and image height/width and are int32.\n\n Returns:\n The new image that will have the shifted bbox location in it along with\n the new bbox that contains the new coordinates.\n '
image_height = tf.to_float(tf.maximum(tf.shape(image)[0], 10))
image_width = tf.to_float(tf.maximum(tf.shape(image)[1], 10))
def clip_y(val):
return tf.clip_by_value(val, 0, (tf.to_int32(image_height) - 1))
def clip_x(val):
return tf.clip_by_value(val, 0, (tf.to_int32(image_width) - 1))
min_y = tf.to_int32((image_height * bbox[0]))
min_x = tf.to_int32((image_width * bbox[1]))
max_y = clip_y(tf.to_int32((image_height * bbox[2])))
max_x = clip_x(tf.to_int32((image_width * bbox[3])))
(bbox_height, bbox_width) = (((max_y - min_y) + 1), ((max_x - min_x) + 1))
image_height = tf.to_int32(image_height)
image_width = tf.to_int32(image_width)
minval_y = clip_y((min_y - tf.to_int32(((pixel_scaling * tf.to_float(bbox_height)) / 2.0))))
maxval_y = clip_y((min_y + tf.to_int32(((pixel_scaling * tf.to_float(bbox_height)) / 2.0))))
minval_x = clip_x((min_x - tf.to_int32(((pixel_scaling * tf.to_float(bbox_width)) / 2.0))))
maxval_x = clip_x((min_x + tf.to_int32(((pixel_scaling * tf.to_float(bbox_width)) / 2.0))))
if (new_min_bbox_coords is None):
unclipped_new_min_y = tf.random_uniform(shape=[], minval=minval_y, maxval=maxval_y, dtype=tf.int32)
unclipped_new_min_x = tf.random_uniform(shape=[], minval=minval_x, maxval=maxval_x, dtype=tf.int32)
else:
(unclipped_new_min_y, unclipped_new_min_x) = (clip_y(new_min_bbox_coords[0]), clip_x(new_min_bbox_coords[1]))
unclipped_new_max_y = ((unclipped_new_min_y + bbox_height) - 1)
unclipped_new_max_x = ((unclipped_new_min_x + bbox_width) - 1)
(new_min_y, new_min_x, new_max_y, new_max_x) = (clip_y(unclipped_new_min_y), clip_x(unclipped_new_min_x), clip_y(unclipped_new_max_y), clip_x(unclipped_new_max_x))
shifted_min_y = ((new_min_y - unclipped_new_min_y) + min_y)
shifted_max_y = (max_y - (unclipped_new_max_y - new_max_y))
shifted_min_x = ((new_min_x - unclipped_new_min_x) + min_x)
shifted_max_x = (max_x - (unclipped_new_max_x - new_max_x))
new_bbox = tf.stack([(tf.to_float(new_min_y) / tf.to_float(image_height)), (tf.to_float(new_min_x) / tf.to_float(image_width)), (tf.to_float(new_max_y) / tf.to_float(image_height)), (tf.to_float(new_max_x) / tf.to_float(image_width))])
bbox_content = image[shifted_min_y:(shifted_max_y + 1), shifted_min_x:(shifted_max_x + 1), :]
def mask_and_add_image(min_y_, min_x_, max_y_, max_x_, mask, content_tensor, image_):
'Applies mask to bbox region in image then adds content_tensor to it.'
mask = tf.pad(mask, [[min_y_, ((image_height - 1) - max_y_)], [min_x_, ((image_width - 1) - max_x_)], [0, 0]], constant_values=1)
content_tensor = tf.pad(content_tensor, [[min_y_, ((image_height - 1) - max_y_)], [min_x_, ((image_width - 1) - max_x_)], [0, 0]], constant_values=0)
return ((image_ * mask) + content_tensor)
mask = tf.zeros_like(image)[min_y:(max_y + 1), min_x:(max_x + 1), :]
grey_tensor = (tf.zeros_like(mask) + replace[0])
image = mask_and_add_image(min_y, min_x, max_y, max_x, mask, grey_tensor, image)
mask = tf.zeros_like(bbox_content)
image = mask_and_add_image(new_min_y, new_min_x, new_max_y, new_max_x, mask, bbox_content, image)
return (image, new_bbox) | -5,648,054,145,612,244,000 | Move the bbox and the image content to a slightly new random location.
Args:
image: 3D uint8 Tensor.
bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)
of type float that represents the normalized coordinates between 0 and 1.
The potential values for the new min corner of the bbox will be between
[old_min - pixel_scaling * bbox_height/2,
old_min - pixel_scaling * bbox_height/2].
pixel_scaling: A float between 0 and 1 that specifies the pixel range
that the new bbox location will be sampled from.
replace: A one or three value 1D tensor to fill empty pixels.
new_min_bbox_coords: If not None, then this is a tuple that specifies the
(min_y, min_x) coordinates of the new bbox. Normally this is randomly
specified, but this allows it to be manually set. The coordinates are
the absolute coordinates between 0 and image height/width and are int32.
Returns:
The new image that will have the shifted bbox location in it along with
the new bbox that contains the new coordinates. | efficientdet/aug/autoaugment.py | random_shift_bbox | datawowio/automl | python | def random_shift_bbox(image, bbox, pixel_scaling, replace, new_min_bbox_coords=None):
'Move the bbox and the image content to a slightly new random location.\n\n Args:\n image: 3D uint8 Tensor.\n bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)\n of type float that represents the normalized coordinates between 0 and 1.\n The potential values for the new min corner of the bbox will be between\n [old_min - pixel_scaling * bbox_height/2,\n old_min - pixel_scaling * bbox_height/2].\n pixel_scaling: A float between 0 and 1 that specifies the pixel range\n that the new bbox location will be sampled from.\n replace: A one or three value 1D tensor to fill empty pixels.\n new_min_bbox_coords: If not None, then this is a tuple that specifies the\n (min_y, min_x) coordinates of the new bbox. Normally this is randomly\n specified, but this allows it to be manually set. The coordinates are\n the absolute coordinates between 0 and image height/width and are int32.\n\n Returns:\n The new image that will have the shifted bbox location in it along with\n the new bbox that contains the new coordinates.\n '
image_height = tf.to_float(tf.maximum(tf.shape(image)[0], 10))
image_width = tf.to_float(tf.maximum(tf.shape(image)[1], 10))
def clip_y(val):
return tf.clip_by_value(val, 0, (tf.to_int32(image_height) - 1))
def clip_x(val):
return tf.clip_by_value(val, 0, (tf.to_int32(image_width) - 1))
min_y = tf.to_int32((image_height * bbox[0]))
min_x = tf.to_int32((image_width * bbox[1]))
max_y = clip_y(tf.to_int32((image_height * bbox[2])))
max_x = clip_x(tf.to_int32((image_width * bbox[3])))
(bbox_height, bbox_width) = (((max_y - min_y) + 1), ((max_x - min_x) + 1))
image_height = tf.to_int32(image_height)
image_width = tf.to_int32(image_width)
minval_y = clip_y((min_y - tf.to_int32(((pixel_scaling * tf.to_float(bbox_height)) / 2.0))))
maxval_y = clip_y((min_y + tf.to_int32(((pixel_scaling * tf.to_float(bbox_height)) / 2.0))))
minval_x = clip_x((min_x - tf.to_int32(((pixel_scaling * tf.to_float(bbox_width)) / 2.0))))
maxval_x = clip_x((min_x + tf.to_int32(((pixel_scaling * tf.to_float(bbox_width)) / 2.0))))
if (new_min_bbox_coords is None):
unclipped_new_min_y = tf.random_uniform(shape=[], minval=minval_y, maxval=maxval_y, dtype=tf.int32)
unclipped_new_min_x = tf.random_uniform(shape=[], minval=minval_x, maxval=maxval_x, dtype=tf.int32)
else:
(unclipped_new_min_y, unclipped_new_min_x) = (clip_y(new_min_bbox_coords[0]), clip_x(new_min_bbox_coords[1]))
unclipped_new_max_y = ((unclipped_new_min_y + bbox_height) - 1)
unclipped_new_max_x = ((unclipped_new_min_x + bbox_width) - 1)
(new_min_y, new_min_x, new_max_y, new_max_x) = (clip_y(unclipped_new_min_y), clip_x(unclipped_new_min_x), clip_y(unclipped_new_max_y), clip_x(unclipped_new_max_x))
shifted_min_y = ((new_min_y - unclipped_new_min_y) + min_y)
shifted_max_y = (max_y - (unclipped_new_max_y - new_max_y))
shifted_min_x = ((new_min_x - unclipped_new_min_x) + min_x)
shifted_max_x = (max_x - (unclipped_new_max_x - new_max_x))
new_bbox = tf.stack([(tf.to_float(new_min_y) / tf.to_float(image_height)), (tf.to_float(new_min_x) / tf.to_float(image_width)), (tf.to_float(new_max_y) / tf.to_float(image_height)), (tf.to_float(new_max_x) / tf.to_float(image_width))])
bbox_content = image[shifted_min_y:(shifted_max_y + 1), shifted_min_x:(shifted_max_x + 1), :]
def mask_and_add_image(min_y_, min_x_, max_y_, max_x_, mask, content_tensor, image_):
'Applies mask to bbox region in image then adds content_tensor to it.'
mask = tf.pad(mask, [[min_y_, ((image_height - 1) - max_y_)], [min_x_, ((image_width - 1) - max_x_)], [0, 0]], constant_values=1)
content_tensor = tf.pad(content_tensor, [[min_y_, ((image_height - 1) - max_y_)], [min_x_, ((image_width - 1) - max_x_)], [0, 0]], constant_values=0)
return ((image_ * mask) + content_tensor)
mask = tf.zeros_like(image)[min_y:(max_y + 1), min_x:(max_x + 1), :]
grey_tensor = (tf.zeros_like(mask) + replace[0])
image = mask_and_add_image(min_y, min_x, max_y, max_x, mask, grey_tensor, image)
mask = tf.zeros_like(bbox_content)
image = mask_and_add_image(new_min_y, new_min_x, new_max_y, new_max_x, mask, bbox_content, image)
return (image, new_bbox) |
def _clip_bbox(min_y, min_x, max_y, max_x):
'Clip bounding box coordinates between 0 and 1.\n\n Args:\n min_y: Normalized bbox coordinate of type float between 0 and 1.\n min_x: Normalized bbox coordinate of type float between 0 and 1.\n max_y: Normalized bbox coordinate of type float between 0 and 1.\n max_x: Normalized bbox coordinate of type float between 0 and 1.\n\n Returns:\n Clipped coordinate values between 0 and 1.\n '
min_y = tf.clip_by_value(min_y, 0.0, 1.0)
min_x = tf.clip_by_value(min_x, 0.0, 1.0)
max_y = tf.clip_by_value(max_y, 0.0, 1.0)
max_x = tf.clip_by_value(max_x, 0.0, 1.0)
return (min_y, min_x, max_y, max_x) | -5,820,401,531,858,483,000 | Clip bounding box coordinates between 0 and 1.
Args:
min_y: Normalized bbox coordinate of type float between 0 and 1.
min_x: Normalized bbox coordinate of type float between 0 and 1.
max_y: Normalized bbox coordinate of type float between 0 and 1.
max_x: Normalized bbox coordinate of type float between 0 and 1.
Returns:
Clipped coordinate values between 0 and 1. | efficientdet/aug/autoaugment.py | _clip_bbox | datawowio/automl | python | def _clip_bbox(min_y, min_x, max_y, max_x):
'Clip bounding box coordinates between 0 and 1.\n\n Args:\n min_y: Normalized bbox coordinate of type float between 0 and 1.\n min_x: Normalized bbox coordinate of type float between 0 and 1.\n max_y: Normalized bbox coordinate of type float between 0 and 1.\n max_x: Normalized bbox coordinate of type float between 0 and 1.\n\n Returns:\n Clipped coordinate values between 0 and 1.\n '
min_y = tf.clip_by_value(min_y, 0.0, 1.0)
min_x = tf.clip_by_value(min_x, 0.0, 1.0)
max_y = tf.clip_by_value(max_y, 0.0, 1.0)
max_x = tf.clip_by_value(max_x, 0.0, 1.0)
return (min_y, min_x, max_y, max_x) |
def _check_bbox_area(min_y, min_x, max_y, max_x, delta=0.05):
'Adjusts bbox coordinates to make sure the area is > 0.\n\n Args:\n min_y: Normalized bbox coordinate of type float between 0 and 1.\n min_x: Normalized bbox coordinate of type float between 0 and 1.\n max_y: Normalized bbox coordinate of type float between 0 and 1.\n max_x: Normalized bbox coordinate of type float between 0 and 1.\n delta: Float, this is used to create a gap of size 2 * delta between\n bbox min/max coordinates that are the same on the boundary.\n This prevents the bbox from having an area of zero.\n\n Returns:\n Tuple of new bbox coordinates between 0 and 1 that will now have a\n guaranteed area > 0.\n '
height = (max_y - min_y)
width = (max_x - min_x)
def _adjust_bbox_boundaries(min_coord, max_coord):
max_coord = tf.maximum(max_coord, (0.0 + delta))
min_coord = tf.minimum(min_coord, (1.0 - delta))
return (min_coord, max_coord)
(min_y, max_y) = tf.cond(tf.equal(height, 0.0), (lambda : _adjust_bbox_boundaries(min_y, max_y)), (lambda : (min_y, max_y)))
(min_x, max_x) = tf.cond(tf.equal(width, 0.0), (lambda : _adjust_bbox_boundaries(min_x, max_x)), (lambda : (min_x, max_x)))
return (min_y, min_x, max_y, max_x) | 68,563,721,215,404,140 | Adjusts bbox coordinates to make sure the area is > 0.
Args:
min_y: Normalized bbox coordinate of type float between 0 and 1.
min_x: Normalized bbox coordinate of type float between 0 and 1.
max_y: Normalized bbox coordinate of type float between 0 and 1.
max_x: Normalized bbox coordinate of type float between 0 and 1.
delta: Float, this is used to create a gap of size 2 * delta between
bbox min/max coordinates that are the same on the boundary.
This prevents the bbox from having an area of zero.
Returns:
Tuple of new bbox coordinates between 0 and 1 that will now have a
guaranteed area > 0. | efficientdet/aug/autoaugment.py | _check_bbox_area | datawowio/automl | python | def _check_bbox_area(min_y, min_x, max_y, max_x, delta=0.05):
'Adjusts bbox coordinates to make sure the area is > 0.\n\n Args:\n min_y: Normalized bbox coordinate of type float between 0 and 1.\n min_x: Normalized bbox coordinate of type float between 0 and 1.\n max_y: Normalized bbox coordinate of type float between 0 and 1.\n max_x: Normalized bbox coordinate of type float between 0 and 1.\n delta: Float, this is used to create a gap of size 2 * delta between\n bbox min/max coordinates that are the same on the boundary.\n This prevents the bbox from having an area of zero.\n\n Returns:\n Tuple of new bbox coordinates between 0 and 1 that will now have a\n guaranteed area > 0.\n '
height = (max_y - min_y)
width = (max_x - min_x)
def _adjust_bbox_boundaries(min_coord, max_coord):
max_coord = tf.maximum(max_coord, (0.0 + delta))
min_coord = tf.minimum(min_coord, (1.0 - delta))
return (min_coord, max_coord)
(min_y, max_y) = tf.cond(tf.equal(height, 0.0), (lambda : _adjust_bbox_boundaries(min_y, max_y)), (lambda : (min_y, max_y)))
(min_x, max_x) = tf.cond(tf.equal(width, 0.0), (lambda : _adjust_bbox_boundaries(min_x, max_x)), (lambda : (min_x, max_x)))
return (min_y, min_x, max_y, max_x) |
def _scale_bbox_only_op_probability(prob):
'Reduce the probability of the bbox-only operation.\n\n Probability is reduced so that we do not distort the content of too many\n bounding boxes that are close to each other. The value of 3.0 was a chosen\n hyper parameter when designing the autoaugment algorithm that we found\n empirically to work well.\n\n Args:\n prob: Float that is the probability of applying the bbox-only operation.\n\n Returns:\n Reduced probability.\n '
return (prob / 3.0) | 8,180,426,613,846,989,000 | Reduce the probability of the bbox-only operation.
Probability is reduced so that we do not distort the content of too many
bounding boxes that are close to each other. The value of 3.0 was a chosen
hyper parameter when designing the autoaugment algorithm that we found
empirically to work well.
Args:
prob: Float that is the probability of applying the bbox-only operation.
Returns:
Reduced probability. | efficientdet/aug/autoaugment.py | _scale_bbox_only_op_probability | datawowio/automl | python | def _scale_bbox_only_op_probability(prob):
'Reduce the probability of the bbox-only operation.\n\n Probability is reduced so that we do not distort the content of too many\n bounding boxes that are close to each other. The value of 3.0 was a chosen\n hyper parameter when designing the autoaugment algorithm that we found\n empirically to work well.\n\n Args:\n prob: Float that is the probability of applying the bbox-only operation.\n\n Returns:\n Reduced probability.\n '
return (prob / 3.0) |
def _apply_bbox_augmentation(image, bbox, augmentation_func, *args):
'Applies augmentation_func to the subsection of image indicated by bbox.\n\n Args:\n image: 3D uint8 Tensor.\n bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)\n of type float that represents the normalized coordinates between 0 and 1.\n augmentation_func: Augmentation function that will be applied to the\n subsection of image.\n *args: Additional parameters that will be passed into augmentation_func\n when it is called.\n\n Returns:\n A modified version of image, where the bbox location in the image will\n have `ugmentation_func applied to it.\n '
image_height = tf.to_float(tf.maximum(tf.shape(image)[0], 10))
image_width = tf.to_float(tf.maximum(tf.shape(image)[1], 10))
min_y = tf.to_int32((image_height * bbox[0]))
min_x = tf.to_int32((image_width * bbox[1]))
max_y = tf.to_int32((image_height * bbox[2]))
max_x = tf.to_int32((image_width * bbox[3]))
image_height = tf.to_int32(image_height)
image_width = tf.to_int32(image_width)
max_y = tf.minimum(max_y, (image_height - 1))
max_x = tf.minimum(max_x, (image_width - 1))
bbox_content = image[min_y:(max_y + 1), min_x:(max_x + 1), :]
augmented_bbox_content = augmentation_func(bbox_content, *args)
augmented_bbox_content = tf.pad(augmented_bbox_content, [[min_y, ((image_height - 1) - max_y)], [min_x, ((image_width - 1) - max_x)], [0, 0]])
mask_tensor = tf.zeros_like(bbox_content)
mask_tensor = tf.pad(mask_tensor, [[min_y, ((image_height - 1) - max_y)], [min_x, ((image_width - 1) - max_x)], [0, 0]], constant_values=1)
image = ((image * mask_tensor) + augmented_bbox_content)
return image | 5,033,668,537,318,786,000 | Applies augmentation_func to the subsection of image indicated by bbox.
Args:
image: 3D uint8 Tensor.
bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)
of type float that represents the normalized coordinates between 0 and 1.
augmentation_func: Augmentation function that will be applied to the
subsection of image.
*args: Additional parameters that will be passed into augmentation_func
when it is called.
Returns:
A modified version of image, where the bbox location in the image will
have `ugmentation_func applied to it. | efficientdet/aug/autoaugment.py | _apply_bbox_augmentation | datawowio/automl | python | def _apply_bbox_augmentation(image, bbox, augmentation_func, *args):
'Applies augmentation_func to the subsection of image indicated by bbox.\n\n Args:\n image: 3D uint8 Tensor.\n bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)\n of type float that represents the normalized coordinates between 0 and 1.\n augmentation_func: Augmentation function that will be applied to the\n subsection of image.\n *args: Additional parameters that will be passed into augmentation_func\n when it is called.\n\n Returns:\n A modified version of image, where the bbox location in the image will\n have `ugmentation_func applied to it.\n '
image_height = tf.to_float(tf.maximum(tf.shape(image)[0], 10))
image_width = tf.to_float(tf.maximum(tf.shape(image)[1], 10))
min_y = tf.to_int32((image_height * bbox[0]))
min_x = tf.to_int32((image_width * bbox[1]))
max_y = tf.to_int32((image_height * bbox[2]))
max_x = tf.to_int32((image_width * bbox[3]))
image_height = tf.to_int32(image_height)
image_width = tf.to_int32(image_width)
max_y = tf.minimum(max_y, (image_height - 1))
max_x = tf.minimum(max_x, (image_width - 1))
bbox_content = image[min_y:(max_y + 1), min_x:(max_x + 1), :]
augmented_bbox_content = augmentation_func(bbox_content, *args)
augmented_bbox_content = tf.pad(augmented_bbox_content, [[min_y, ((image_height - 1) - max_y)], [min_x, ((image_width - 1) - max_x)], [0, 0]])
mask_tensor = tf.zeros_like(bbox_content)
mask_tensor = tf.pad(mask_tensor, [[min_y, ((image_height - 1) - max_y)], [min_x, ((image_width - 1) - max_x)], [0, 0]], constant_values=1)
image = ((image * mask_tensor) + augmented_bbox_content)
return image |
def _concat_bbox(bbox, bboxes):
'Helper function that concats bbox to bboxes along the first dimension.'
bboxes_sum_check = tf.reduce_sum(bboxes)
bbox = tf.expand_dims(bbox, 0)
bboxes = tf.cond(tf.equal(bboxes_sum_check, (- 4.0)), (lambda : bbox), (lambda : tf.concat([bboxes, bbox], 0)))
return bboxes | 9,145,103,630,591,172,000 | Helper function that concats bbox to bboxes along the first dimension. | efficientdet/aug/autoaugment.py | _concat_bbox | datawowio/automl | python | def _concat_bbox(bbox, bboxes):
bboxes_sum_check = tf.reduce_sum(bboxes)
bbox = tf.expand_dims(bbox, 0)
bboxes = tf.cond(tf.equal(bboxes_sum_check, (- 4.0)), (lambda : bbox), (lambda : tf.concat([bboxes, bbox], 0)))
return bboxes |
def _apply_bbox_augmentation_wrapper(image, bbox, new_bboxes, prob, augmentation_func, func_changes_bbox, *args):
'Applies _apply_bbox_augmentation with probability prob.\n\n Args:\n image: 3D uint8 Tensor.\n bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)\n of type float that represents the normalized coordinates between 0 and 1.\n new_bboxes: 2D Tensor that is a list of the bboxes in the image after they\n have been altered by aug_func. These will only be changed when\n func_changes_bbox is set to true. Each bbox has 4 elements\n (min_y, min_x, max_y, max_x) of type float that are the normalized\n bbox coordinates between 0 and 1.\n prob: Float that is the probability of applying _apply_bbox_augmentation.\n augmentation_func: Augmentation function that will be applied to the\n subsection of image.\n func_changes_bbox: Boolean. Does augmentation_func return bbox in addition\n to image.\n *args: Additional parameters that will be passed into augmentation_func\n when it is called.\n\n Returns:\n A tuple. Fist element is a modified version of image, where the bbox\n location in the image will have augmentation_func applied to it if it is\n chosen to be called with probability `prob`. The second element is a\n Tensor of Tensors of length 4 that will contain the altered bbox after\n applying augmentation_func.\n '
should_apply_op = tf.cast(tf.floor((tf.random_uniform([], dtype=tf.float32) + prob)), tf.bool)
if func_changes_bbox:
(augmented_image, bbox) = tf.cond(should_apply_op, (lambda : augmentation_func(image, bbox, *args)), (lambda : (image, bbox)))
else:
augmented_image = tf.cond(should_apply_op, (lambda : _apply_bbox_augmentation(image, bbox, augmentation_func, *args)), (lambda : image))
new_bboxes = _concat_bbox(bbox, new_bboxes)
return (augmented_image, new_bboxes) | -6,801,094,433,672,039,000 | Applies _apply_bbox_augmentation with probability prob.
Args:
image: 3D uint8 Tensor.
bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)
of type float that represents the normalized coordinates between 0 and 1.
new_bboxes: 2D Tensor that is a list of the bboxes in the image after they
have been altered by aug_func. These will only be changed when
func_changes_bbox is set to true. Each bbox has 4 elements
(min_y, min_x, max_y, max_x) of type float that are the normalized
bbox coordinates between 0 and 1.
prob: Float that is the probability of applying _apply_bbox_augmentation.
augmentation_func: Augmentation function that will be applied to the
subsection of image.
func_changes_bbox: Boolean. Does augmentation_func return bbox in addition
to image.
*args: Additional parameters that will be passed into augmentation_func
when it is called.
Returns:
A tuple. Fist element is a modified version of image, where the bbox
location in the image will have augmentation_func applied to it if it is
chosen to be called with probability `prob`. The second element is a
Tensor of Tensors of length 4 that will contain the altered bbox after
applying augmentation_func. | efficientdet/aug/autoaugment.py | _apply_bbox_augmentation_wrapper | datawowio/automl | python | def _apply_bbox_augmentation_wrapper(image, bbox, new_bboxes, prob, augmentation_func, func_changes_bbox, *args):
'Applies _apply_bbox_augmentation with probability prob.\n\n Args:\n image: 3D uint8 Tensor.\n bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)\n of type float that represents the normalized coordinates between 0 and 1.\n new_bboxes: 2D Tensor that is a list of the bboxes in the image after they\n have been altered by aug_func. These will only be changed when\n func_changes_bbox is set to true. Each bbox has 4 elements\n (min_y, min_x, max_y, max_x) of type float that are the normalized\n bbox coordinates between 0 and 1.\n prob: Float that is the probability of applying _apply_bbox_augmentation.\n augmentation_func: Augmentation function that will be applied to the\n subsection of image.\n func_changes_bbox: Boolean. Does augmentation_func return bbox in addition\n to image.\n *args: Additional parameters that will be passed into augmentation_func\n when it is called.\n\n Returns:\n A tuple. Fist element is a modified version of image, where the bbox\n location in the image will have augmentation_func applied to it if it is\n chosen to be called with probability `prob`. The second element is a\n Tensor of Tensors of length 4 that will contain the altered bbox after\n applying augmentation_func.\n '
should_apply_op = tf.cast(tf.floor((tf.random_uniform([], dtype=tf.float32) + prob)), tf.bool)
if func_changes_bbox:
(augmented_image, bbox) = tf.cond(should_apply_op, (lambda : augmentation_func(image, bbox, *args)), (lambda : (image, bbox)))
else:
augmented_image = tf.cond(should_apply_op, (lambda : _apply_bbox_augmentation(image, bbox, augmentation_func, *args)), (lambda : image))
new_bboxes = _concat_bbox(bbox, new_bboxes)
return (augmented_image, new_bboxes) |
def _apply_multi_bbox_augmentation(image, bboxes, prob, aug_func, func_changes_bbox, *args):
'Applies aug_func to the image for each bbox in bboxes.\n\n Args:\n image: 3D uint8 Tensor.\n bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox\n has 4 elements (min_y, min_x, max_y, max_x) of type float.\n prob: Float that is the probability of applying aug_func to a specific\n bounding box within the image.\n aug_func: Augmentation function that will be applied to the\n subsections of image indicated by the bbox values in bboxes.\n func_changes_bbox: Boolean. Does augmentation_func return bbox in addition\n to image.\n *args: Additional parameters that will be passed into augmentation_func\n when it is called.\n\n Returns:\n A modified version of image, where each bbox location in the image will\n have augmentation_func applied to it if it is chosen to be called with\n probability prob independently across all bboxes. Also the final\n bboxes are returned that will be unchanged if func_changes_bbox is set to\n false and if true, the new altered ones will be returned.\n '
new_bboxes = tf.constant(_INVALID_BOX)
bboxes = tf.cond(tf.equal(tf.shape(bboxes)[0], 0), (lambda : tf.constant(_INVALID_BOX)), (lambda : bboxes))
bboxes = tf.ensure_shape(bboxes, (None, 4))
wrapped_aug_func = (lambda _image, bbox, _new_bboxes: _apply_bbox_augmentation_wrapper(_image, bbox, _new_bboxes, prob, aug_func, func_changes_bbox, *args))
num_bboxes = tf.shape(bboxes)[0]
idx = tf.constant(0)
cond = (lambda _idx, _images_and_bboxes: tf.less(_idx, num_bboxes))
if (not func_changes_bbox):
loop_bboxes = tf.random.shuffle(bboxes)
else:
loop_bboxes = bboxes
body = (lambda _idx, _images_and_bboxes: [(_idx + 1), wrapped_aug_func(_images_and_bboxes[0], loop_bboxes[_idx], _images_and_bboxes[1])])
(_, (image, new_bboxes)) = tf.while_loop(cond, body, [idx, (image, new_bboxes)], shape_invariants=[idx.get_shape(), (image.get_shape(), tf.TensorShape([None, 4]))])
if func_changes_bbox:
final_bboxes = new_bboxes
else:
final_bboxes = bboxes
return (image, final_bboxes) | 102,916,792,991,740,450 | Applies aug_func to the image for each bbox in bboxes.
Args:
image: 3D uint8 Tensor.
bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox
has 4 elements (min_y, min_x, max_y, max_x) of type float.
prob: Float that is the probability of applying aug_func to a specific
bounding box within the image.
aug_func: Augmentation function that will be applied to the
subsections of image indicated by the bbox values in bboxes.
func_changes_bbox: Boolean. Does augmentation_func return bbox in addition
to image.
*args: Additional parameters that will be passed into augmentation_func
when it is called.
Returns:
A modified version of image, where each bbox location in the image will
have augmentation_func applied to it if it is chosen to be called with
probability prob independently across all bboxes. Also the final
bboxes are returned that will be unchanged if func_changes_bbox is set to
false and if true, the new altered ones will be returned. | efficientdet/aug/autoaugment.py | _apply_multi_bbox_augmentation | datawowio/automl | python | def _apply_multi_bbox_augmentation(image, bboxes, prob, aug_func, func_changes_bbox, *args):
'Applies aug_func to the image for each bbox in bboxes.\n\n Args:\n image: 3D uint8 Tensor.\n bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox\n has 4 elements (min_y, min_x, max_y, max_x) of type float.\n prob: Float that is the probability of applying aug_func to a specific\n bounding box within the image.\n aug_func: Augmentation function that will be applied to the\n subsections of image indicated by the bbox values in bboxes.\n func_changes_bbox: Boolean. Does augmentation_func return bbox in addition\n to image.\n *args: Additional parameters that will be passed into augmentation_func\n when it is called.\n\n Returns:\n A modified version of image, where each bbox location in the image will\n have augmentation_func applied to it if it is chosen to be called with\n probability prob independently across all bboxes. Also the final\n bboxes are returned that will be unchanged if func_changes_bbox is set to\n false and if true, the new altered ones will be returned.\n '
new_bboxes = tf.constant(_INVALID_BOX)
bboxes = tf.cond(tf.equal(tf.shape(bboxes)[0], 0), (lambda : tf.constant(_INVALID_BOX)), (lambda : bboxes))
bboxes = tf.ensure_shape(bboxes, (None, 4))
wrapped_aug_func = (lambda _image, bbox, _new_bboxes: _apply_bbox_augmentation_wrapper(_image, bbox, _new_bboxes, prob, aug_func, func_changes_bbox, *args))
num_bboxes = tf.shape(bboxes)[0]
idx = tf.constant(0)
cond = (lambda _idx, _images_and_bboxes: tf.less(_idx, num_bboxes))
if (not func_changes_bbox):
loop_bboxes = tf.random.shuffle(bboxes)
else:
loop_bboxes = bboxes
body = (lambda _idx, _images_and_bboxes: [(_idx + 1), wrapped_aug_func(_images_and_bboxes[0], loop_bboxes[_idx], _images_and_bboxes[1])])
(_, (image, new_bboxes)) = tf.while_loop(cond, body, [idx, (image, new_bboxes)], shape_invariants=[idx.get_shape(), (image.get_shape(), tf.TensorShape([None, 4]))])
if func_changes_bbox:
final_bboxes = new_bboxes
else:
final_bboxes = bboxes
return (image, final_bboxes) |
def _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob, aug_func, func_changes_bbox, *args):
'Checks to be sure num bboxes > 0 before calling inner function.'
num_bboxes = tf.shape(bboxes)[0]
(image, bboxes) = tf.cond(tf.equal(num_bboxes, 0), (lambda : (image, bboxes)), (lambda : _apply_multi_bbox_augmentation(image, bboxes, prob, aug_func, func_changes_bbox, *args)))
return (image, bboxes) | -2,794,229,445,988,702,000 | Checks to be sure num bboxes > 0 before calling inner function. | efficientdet/aug/autoaugment.py | _apply_multi_bbox_augmentation_wrapper | datawowio/automl | python | def _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob, aug_func, func_changes_bbox, *args):
num_bboxes = tf.shape(bboxes)[0]
(image, bboxes) = tf.cond(tf.equal(num_bboxes, 0), (lambda : (image, bboxes)), (lambda : _apply_multi_bbox_augmentation(image, bboxes, prob, aug_func, func_changes_bbox, *args)))
return (image, bboxes) |
def rotate_only_bboxes(image, bboxes, prob, degrees, replace):
'Apply rotate to each bbox in the image with probability prob.'
func_changes_bbox = False
prob = _scale_bbox_only_op_probability(prob)
return _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob, rotate, func_changes_bbox, degrees, replace) | 9,211,649,917,027,160,000 | Apply rotate to each bbox in the image with probability prob. | efficientdet/aug/autoaugment.py | rotate_only_bboxes | datawowio/automl | python | def rotate_only_bboxes(image, bboxes, prob, degrees, replace):
func_changes_bbox = False
prob = _scale_bbox_only_op_probability(prob)
return _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob, rotate, func_changes_bbox, degrees, replace) |
def shear_x_only_bboxes(image, bboxes, prob, level, replace):
'Apply shear_x to each bbox in the image with probability prob.'
func_changes_bbox = False
prob = _scale_bbox_only_op_probability(prob)
return _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob, shear_x, func_changes_bbox, level, replace) | 5,920,012,366,805,690,000 | Apply shear_x to each bbox in the image with probability prob. | efficientdet/aug/autoaugment.py | shear_x_only_bboxes | datawowio/automl | python | def shear_x_only_bboxes(image, bboxes, prob, level, replace):
func_changes_bbox = False
prob = _scale_bbox_only_op_probability(prob)
return _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob, shear_x, func_changes_bbox, level, replace) |
def shear_y_only_bboxes(image, bboxes, prob, level, replace):
'Apply shear_y to each bbox in the image with probability prob.'
func_changes_bbox = False
prob = _scale_bbox_only_op_probability(prob)
return _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob, shear_y, func_changes_bbox, level, replace) | 7,922,629,001,002,101,000 | Apply shear_y to each bbox in the image with probability prob. | efficientdet/aug/autoaugment.py | shear_y_only_bboxes | datawowio/automl | python | def shear_y_only_bboxes(image, bboxes, prob, level, replace):
func_changes_bbox = False
prob = _scale_bbox_only_op_probability(prob)
return _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob, shear_y, func_changes_bbox, level, replace) |
def translate_x_only_bboxes(image, bboxes, prob, pixels, replace):
'Apply translate_x to each bbox in the image with probability prob.'
func_changes_bbox = False
prob = _scale_bbox_only_op_probability(prob)
return _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob, translate_x, func_changes_bbox, pixels, replace) | -460,229,343,365,831,800 | Apply translate_x to each bbox in the image with probability prob. | efficientdet/aug/autoaugment.py | translate_x_only_bboxes | datawowio/automl | python | def translate_x_only_bboxes(image, bboxes, prob, pixels, replace):
func_changes_bbox = False
prob = _scale_bbox_only_op_probability(prob)
return _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob, translate_x, func_changes_bbox, pixels, replace) |
def translate_y_only_bboxes(image, bboxes, prob, pixels, replace):
'Apply translate_y to each bbox in the image with probability prob.'
func_changes_bbox = False
prob = _scale_bbox_only_op_probability(prob)
return _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob, translate_y, func_changes_bbox, pixels, replace) | -888,010,208,539,744,100 | Apply translate_y to each bbox in the image with probability prob. | efficientdet/aug/autoaugment.py | translate_y_only_bboxes | datawowio/automl | python | def translate_y_only_bboxes(image, bboxes, prob, pixels, replace):
func_changes_bbox = False
prob = _scale_bbox_only_op_probability(prob)
return _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob, translate_y, func_changes_bbox, pixels, replace) |
def flip_only_bboxes(image, bboxes, prob):
'Apply flip_lr to each bbox in the image with probability prob.'
func_changes_bbox = False
prob = _scale_bbox_only_op_probability(prob)
return _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob, tf.image.flip_left_right, func_changes_bbox) | -5,039,183,936,218,054,000 | Apply flip_lr to each bbox in the image with probability prob. | efficientdet/aug/autoaugment.py | flip_only_bboxes | datawowio/automl | python | def flip_only_bboxes(image, bboxes, prob):
func_changes_bbox = False
prob = _scale_bbox_only_op_probability(prob)
return _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob, tf.image.flip_left_right, func_changes_bbox) |
def solarize_only_bboxes(image, bboxes, prob, threshold):
'Apply solarize to each bbox in the image with probability prob.'
func_changes_bbox = False
prob = _scale_bbox_only_op_probability(prob)
return _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob, solarize, func_changes_bbox, threshold) | -7,773,348,117,398,861,000 | Apply solarize to each bbox in the image with probability prob. | efficientdet/aug/autoaugment.py | solarize_only_bboxes | datawowio/automl | python | def solarize_only_bboxes(image, bboxes, prob, threshold):
func_changes_bbox = False
prob = _scale_bbox_only_op_probability(prob)
return _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob, solarize, func_changes_bbox, threshold) |
def equalize_only_bboxes(image, bboxes, prob):
'Apply equalize to each bbox in the image with probability prob.'
func_changes_bbox = False
prob = _scale_bbox_only_op_probability(prob)
return _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob, equalize, func_changes_bbox) | -6,543,237,160,596,510,000 | Apply equalize to each bbox in the image with probability prob. | efficientdet/aug/autoaugment.py | equalize_only_bboxes | datawowio/automl | python | def equalize_only_bboxes(image, bboxes, prob):
func_changes_bbox = False
prob = _scale_bbox_only_op_probability(prob)
return _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob, equalize, func_changes_bbox) |
def cutout_only_bboxes(image, bboxes, prob, pad_size, replace):
'Apply cutout to each bbox in the image with probability prob.'
func_changes_bbox = False
prob = _scale_bbox_only_op_probability(prob)
return _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob, cutout, func_changes_bbox, pad_size, replace) | -2,471,233,948,783,666,000 | Apply cutout to each bbox in the image with probability prob. | efficientdet/aug/autoaugment.py | cutout_only_bboxes | datawowio/automl | python | def cutout_only_bboxes(image, bboxes, prob, pad_size, replace):
func_changes_bbox = False
prob = _scale_bbox_only_op_probability(prob)
return _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob, cutout, func_changes_bbox, pad_size, replace) |
def _rotate_bbox(bbox, image_height, image_width, degrees):
'Rotates the bbox coordinated by degrees.\n\n Args:\n bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)\n of type float that represents the normalized coordinates between 0 and 1.\n image_height: Int, height of the image.\n image_width: Int, height of the image.\n degrees: Float, a scalar angle in degrees to rotate all images by. If\n degrees is positive the image will be rotated clockwise otherwise it will\n be rotated counterclockwise.\n\n Returns:\n A tensor of the same shape as bbox, but now with the rotated coordinates.\n '
(image_height, image_width) = (tf.to_float(image_height), tf.to_float(image_width))
degrees_to_radians = (math.pi / 180.0)
radians = (degrees * degrees_to_radians)
min_y = (- tf.to_int32((image_height * (bbox[0] - 0.5))))
min_x = tf.to_int32((image_width * (bbox[1] - 0.5)))
max_y = (- tf.to_int32((image_height * (bbox[2] - 0.5))))
max_x = tf.to_int32((image_width * (bbox[3] - 0.5)))
coordinates = tf.stack([[min_y, min_x], [min_y, max_x], [max_y, min_x], [max_y, max_x]])
coordinates = tf.cast(coordinates, tf.float32)
rotation_matrix = tf.stack([[tf.cos(radians), tf.sin(radians)], [(- tf.sin(radians)), tf.cos(radians)]])
new_coords = tf.cast(tf.matmul(rotation_matrix, tf.transpose(coordinates)), tf.int32)
min_y = (- ((tf.to_float(tf.reduce_max(new_coords[0, :])) / image_height) - 0.5))
min_x = ((tf.to_float(tf.reduce_min(new_coords[1, :])) / image_width) + 0.5)
max_y = (- ((tf.to_float(tf.reduce_min(new_coords[0, :])) / image_height) - 0.5))
max_x = ((tf.to_float(tf.reduce_max(new_coords[1, :])) / image_width) + 0.5)
(min_y, min_x, max_y, max_x) = _clip_bbox(min_y, min_x, max_y, max_x)
(min_y, min_x, max_y, max_x) = _check_bbox_area(min_y, min_x, max_y, max_x)
return tf.stack([min_y, min_x, max_y, max_x]) | 6,211,981,566,521,351,000 | Rotates the bbox coordinated by degrees.
Args:
bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)
of type float that represents the normalized coordinates between 0 and 1.
image_height: Int, height of the image.
image_width: Int, height of the image.
degrees: Float, a scalar angle in degrees to rotate all images by. If
degrees is positive the image will be rotated clockwise otherwise it will
be rotated counterclockwise.
Returns:
A tensor of the same shape as bbox, but now with the rotated coordinates. | efficientdet/aug/autoaugment.py | _rotate_bbox | datawowio/automl | python | def _rotate_bbox(bbox, image_height, image_width, degrees):
'Rotates the bbox coordinated by degrees.\n\n Args:\n bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)\n of type float that represents the normalized coordinates between 0 and 1.\n image_height: Int, height of the image.\n image_width: Int, height of the image.\n degrees: Float, a scalar angle in degrees to rotate all images by. If\n degrees is positive the image will be rotated clockwise otherwise it will\n be rotated counterclockwise.\n\n Returns:\n A tensor of the same shape as bbox, but now with the rotated coordinates.\n '
(image_height, image_width) = (tf.to_float(image_height), tf.to_float(image_width))
degrees_to_radians = (math.pi / 180.0)
radians = (degrees * degrees_to_radians)
min_y = (- tf.to_int32((image_height * (bbox[0] - 0.5))))
min_x = tf.to_int32((image_width * (bbox[1] - 0.5)))
max_y = (- tf.to_int32((image_height * (bbox[2] - 0.5))))
max_x = tf.to_int32((image_width * (bbox[3] - 0.5)))
coordinates = tf.stack([[min_y, min_x], [min_y, max_x], [max_y, min_x], [max_y, max_x]])
coordinates = tf.cast(coordinates, tf.float32)
rotation_matrix = tf.stack([[tf.cos(radians), tf.sin(radians)], [(- tf.sin(radians)), tf.cos(radians)]])
new_coords = tf.cast(tf.matmul(rotation_matrix, tf.transpose(coordinates)), tf.int32)
min_y = (- ((tf.to_float(tf.reduce_max(new_coords[0, :])) / image_height) - 0.5))
min_x = ((tf.to_float(tf.reduce_min(new_coords[1, :])) / image_width) + 0.5)
max_y = (- ((tf.to_float(tf.reduce_min(new_coords[0, :])) / image_height) - 0.5))
max_x = ((tf.to_float(tf.reduce_max(new_coords[1, :])) / image_width) + 0.5)
(min_y, min_x, max_y, max_x) = _clip_bbox(min_y, min_x, max_y, max_x)
(min_y, min_x, max_y, max_x) = _check_bbox_area(min_y, min_x, max_y, max_x)
return tf.stack([min_y, min_x, max_y, max_x]) |
def rotate_with_bboxes(image, bboxes, degrees, replace):
'Equivalent of PIL Rotate that rotates the image and bbox.\n\n Args:\n image: 3D uint8 Tensor.\n bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox\n has 4 elements (min_y, min_x, max_y, max_x) of type float.\n degrees: Float, a scalar angle in degrees to rotate all images by. If\n degrees is positive the image will be rotated clockwise otherwise it will\n be rotated counterclockwise.\n replace: A one or three value 1D tensor to fill empty pixels.\n\n Returns:\n A tuple containing a 3D uint8 Tensor that will be the result of rotating\n image by degrees. The second element of the tuple is bboxes, where now\n the coordinates will be shifted to reflect the rotated image.\n '
image = rotate(image, degrees, replace)
image_height = tf.shape(image)[0]
image_width = tf.shape(image)[1]
wrapped_rotate_bbox = (lambda bbox: _rotate_bbox(bbox, image_height, image_width, degrees))
bboxes = tf.map_fn(wrapped_rotate_bbox, bboxes)
return (image, bboxes) | -3,447,364,672,112,616,400 | Equivalent of PIL Rotate that rotates the image and bbox.
Args:
image: 3D uint8 Tensor.
bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox
has 4 elements (min_y, min_x, max_y, max_x) of type float.
degrees: Float, a scalar angle in degrees to rotate all images by. If
degrees is positive the image will be rotated clockwise otherwise it will
be rotated counterclockwise.
replace: A one or three value 1D tensor to fill empty pixels.
Returns:
A tuple containing a 3D uint8 Tensor that will be the result of rotating
image by degrees. The second element of the tuple is bboxes, where now
the coordinates will be shifted to reflect the rotated image. | efficientdet/aug/autoaugment.py | rotate_with_bboxes | datawowio/automl | python | def rotate_with_bboxes(image, bboxes, degrees, replace):
'Equivalent of PIL Rotate that rotates the image and bbox.\n\n Args:\n image: 3D uint8 Tensor.\n bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox\n has 4 elements (min_y, min_x, max_y, max_x) of type float.\n degrees: Float, a scalar angle in degrees to rotate all images by. If\n degrees is positive the image will be rotated clockwise otherwise it will\n be rotated counterclockwise.\n replace: A one or three value 1D tensor to fill empty pixels.\n\n Returns:\n A tuple containing a 3D uint8 Tensor that will be the result of rotating\n image by degrees. The second element of the tuple is bboxes, where now\n the coordinates will be shifted to reflect the rotated image.\n '
image = rotate(image, degrees, replace)
image_height = tf.shape(image)[0]
image_width = tf.shape(image)[1]
wrapped_rotate_bbox = (lambda bbox: _rotate_bbox(bbox, image_height, image_width, degrees))
bboxes = tf.map_fn(wrapped_rotate_bbox, bboxes)
return (image, bboxes) |
def translate_x(image, pixels, replace):
'Equivalent of PIL Translate in X dimension.'
image = image_ops.translate(wrap(image), [(- pixels), 0])
return unwrap(image, replace) | -3,514,625,783,606,751,000 | Equivalent of PIL Translate in X dimension. | efficientdet/aug/autoaugment.py | translate_x | datawowio/automl | python | def translate_x(image, pixels, replace):
image = image_ops.translate(wrap(image), [(- pixels), 0])
return unwrap(image, replace) |
def translate_y(image, pixels, replace):
'Equivalent of PIL Translate in Y dimension.'
image = image_ops.translate(wrap(image), [0, (- pixels)])
return unwrap(image, replace) | -3,311,760,775,496,658,400 | Equivalent of PIL Translate in Y dimension. | efficientdet/aug/autoaugment.py | translate_y | datawowio/automl | python | def translate_y(image, pixels, replace):
image = image_ops.translate(wrap(image), [0, (- pixels)])
return unwrap(image, replace) |
def _shift_bbox(bbox, image_height, image_width, pixels, shift_horizontal):
'Shifts the bbox coordinates by pixels.\n\n Args:\n bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)\n of type float that represents the normalized coordinates between 0 and 1.\n image_height: Int, height of the image.\n image_width: Int, width of the image.\n pixels: An int. How many pixels to shift the bbox.\n shift_horizontal: Boolean. If true then shift in X dimension else shift in\n Y dimension.\n\n Returns:\n A tensor of the same shape as bbox, but now with the shifted coordinates.\n '
pixels = tf.to_int32(pixels)
min_y = tf.to_int32((tf.to_float(image_height) * bbox[0]))
min_x = tf.to_int32((tf.to_float(image_width) * bbox[1]))
max_y = tf.to_int32((tf.to_float(image_height) * bbox[2]))
max_x = tf.to_int32((tf.to_float(image_width) * bbox[3]))
if shift_horizontal:
min_x = tf.maximum(0, (min_x - pixels))
max_x = tf.minimum(image_width, (max_x - pixels))
else:
min_y = tf.maximum(0, (min_y - pixels))
max_y = tf.minimum(image_height, (max_y - pixels))
min_y = (tf.to_float(min_y) / tf.to_float(image_height))
min_x = (tf.to_float(min_x) / tf.to_float(image_width))
max_y = (tf.to_float(max_y) / tf.to_float(image_height))
max_x = (tf.to_float(max_x) / tf.to_float(image_width))
(min_y, min_x, max_y, max_x) = _clip_bbox(min_y, min_x, max_y, max_x)
(min_y, min_x, max_y, max_x) = _check_bbox_area(min_y, min_x, max_y, max_x)
return tf.stack([min_y, min_x, max_y, max_x]) | -6,072,056,995,610,296,000 | Shifts the bbox coordinates by pixels.
Args:
bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)
of type float that represents the normalized coordinates between 0 and 1.
image_height: Int, height of the image.
image_width: Int, width of the image.
pixels: An int. How many pixels to shift the bbox.
shift_horizontal: Boolean. If true then shift in X dimension else shift in
Y dimension.
Returns:
A tensor of the same shape as bbox, but now with the shifted coordinates. | efficientdet/aug/autoaugment.py | _shift_bbox | datawowio/automl | python | def _shift_bbox(bbox, image_height, image_width, pixels, shift_horizontal):
'Shifts the bbox coordinates by pixels.\n\n Args:\n bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)\n of type float that represents the normalized coordinates between 0 and 1.\n image_height: Int, height of the image.\n image_width: Int, width of the image.\n pixels: An int. How many pixels to shift the bbox.\n shift_horizontal: Boolean. If true then shift in X dimension else shift in\n Y dimension.\n\n Returns:\n A tensor of the same shape as bbox, but now with the shifted coordinates.\n '
pixels = tf.to_int32(pixels)
min_y = tf.to_int32((tf.to_float(image_height) * bbox[0]))
min_x = tf.to_int32((tf.to_float(image_width) * bbox[1]))
max_y = tf.to_int32((tf.to_float(image_height) * bbox[2]))
max_x = tf.to_int32((tf.to_float(image_width) * bbox[3]))
if shift_horizontal:
min_x = tf.maximum(0, (min_x - pixels))
max_x = tf.minimum(image_width, (max_x - pixels))
else:
min_y = tf.maximum(0, (min_y - pixels))
max_y = tf.minimum(image_height, (max_y - pixels))
min_y = (tf.to_float(min_y) / tf.to_float(image_height))
min_x = (tf.to_float(min_x) / tf.to_float(image_width))
max_y = (tf.to_float(max_y) / tf.to_float(image_height))
max_x = (tf.to_float(max_x) / tf.to_float(image_width))
(min_y, min_x, max_y, max_x) = _clip_bbox(min_y, min_x, max_y, max_x)
(min_y, min_x, max_y, max_x) = _check_bbox_area(min_y, min_x, max_y, max_x)
return tf.stack([min_y, min_x, max_y, max_x]) |
def translate_bbox(image, bboxes, pixels, replace, shift_horizontal):
'Equivalent of PIL Translate in X/Y dimension that shifts image and bbox.\n\n Args:\n image: 3D uint8 Tensor.\n bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox\n has 4 elements (min_y, min_x, max_y, max_x) of type float with values\n between [0, 1].\n pixels: An int. How many pixels to shift the image and bboxes\n replace: A one or three value 1D tensor to fill empty pixels.\n shift_horizontal: Boolean. If true then shift in X dimension else shift in\n Y dimension.\n\n Returns:\n A tuple containing a 3D uint8 Tensor that will be the result of translating\n image by pixels. The second element of the tuple is bboxes, where now\n the coordinates will be shifted to reflect the shifted image.\n '
if shift_horizontal:
image = translate_x(image, pixels, replace)
else:
image = translate_y(image, pixels, replace)
image_height = tf.shape(image)[0]
image_width = tf.shape(image)[1]
wrapped_shift_bbox = (lambda bbox: _shift_bbox(bbox, image_height, image_width, pixels, shift_horizontal))
bboxes = tf.map_fn(wrapped_shift_bbox, bboxes)
return (image, bboxes) | -1,837,703,549,154,977,800 | Equivalent of PIL Translate in X/Y dimension that shifts image and bbox.
Args:
image: 3D uint8 Tensor.
bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox
has 4 elements (min_y, min_x, max_y, max_x) of type float with values
between [0, 1].
pixels: An int. How many pixels to shift the image and bboxes
replace: A one or three value 1D tensor to fill empty pixels.
shift_horizontal: Boolean. If true then shift in X dimension else shift in
Y dimension.
Returns:
A tuple containing a 3D uint8 Tensor that will be the result of translating
image by pixels. The second element of the tuple is bboxes, where now
the coordinates will be shifted to reflect the shifted image. | efficientdet/aug/autoaugment.py | translate_bbox | datawowio/automl | python | def translate_bbox(image, bboxes, pixels, replace, shift_horizontal):
'Equivalent of PIL Translate in X/Y dimension that shifts image and bbox.\n\n Args:\n image: 3D uint8 Tensor.\n bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox\n has 4 elements (min_y, min_x, max_y, max_x) of type float with values\n between [0, 1].\n pixels: An int. How many pixels to shift the image and bboxes\n replace: A one or three value 1D tensor to fill empty pixels.\n shift_horizontal: Boolean. If true then shift in X dimension else shift in\n Y dimension.\n\n Returns:\n A tuple containing a 3D uint8 Tensor that will be the result of translating\n image by pixels. The second element of the tuple is bboxes, where now\n the coordinates will be shifted to reflect the shifted image.\n '
if shift_horizontal:
image = translate_x(image, pixels, replace)
else:
image = translate_y(image, pixels, replace)
image_height = tf.shape(image)[0]
image_width = tf.shape(image)[1]
wrapped_shift_bbox = (lambda bbox: _shift_bbox(bbox, image_height, image_width, pixels, shift_horizontal))
bboxes = tf.map_fn(wrapped_shift_bbox, bboxes)
return (image, bboxes) |
def shear_x(image, level, replace):
'Equivalent of PIL Shearing in X dimension.'
image = image_ops.transform(wrap(image), [1.0, level, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0])
return unwrap(image, replace) | -6,123,410,436,435,485,000 | Equivalent of PIL Shearing in X dimension. | efficientdet/aug/autoaugment.py | shear_x | datawowio/automl | python | def shear_x(image, level, replace):
image = image_ops.transform(wrap(image), [1.0, level, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0])
return unwrap(image, replace) |
def shear_y(image, level, replace):
'Equivalent of PIL Shearing in Y dimension.'
image = image_ops.transform(wrap(image), [1.0, 0.0, 0.0, level, 1.0, 0.0, 0.0, 0.0])
return unwrap(image, replace) | -7,747,551,437,542,087,000 | Equivalent of PIL Shearing in Y dimension. | efficientdet/aug/autoaugment.py | shear_y | datawowio/automl | python | def shear_y(image, level, replace):
image = image_ops.transform(wrap(image), [1.0, 0.0, 0.0, level, 1.0, 0.0, 0.0, 0.0])
return unwrap(image, replace) |
def _shear_bbox(bbox, image_height, image_width, level, shear_horizontal):
'Shifts the bbox according to how the image was sheared.\n\n Args:\n bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)\n of type float that represents the normalized coordinates between 0 and 1.\n image_height: Int, height of the image.\n image_width: Int, height of the image.\n level: Float. How much to shear the image.\n shear_horizontal: If true then shear in X dimension else shear in\n the Y dimension.\n\n Returns:\n A tensor of the same shape as bbox, but now with the shifted coordinates.\n '
(image_height, image_width) = (tf.to_float(image_height), tf.to_float(image_width))
min_y = tf.to_int32((image_height * bbox[0]))
min_x = tf.to_int32((image_width * bbox[1]))
max_y = tf.to_int32((image_height * bbox[2]))
max_x = tf.to_int32((image_width * bbox[3]))
coordinates = tf.stack([[min_y, min_x], [min_y, max_x], [max_y, min_x], [max_y, max_x]])
coordinates = tf.cast(coordinates, tf.float32)
if shear_horizontal:
translation_matrix = tf.stack([[1, 0], [(- level), 1]])
else:
translation_matrix = tf.stack([[1, (- level)], [0, 1]])
translation_matrix = tf.cast(translation_matrix, tf.float32)
new_coords = tf.cast(tf.matmul(translation_matrix, tf.transpose(coordinates)), tf.int32)
min_y = (tf.to_float(tf.reduce_min(new_coords[0, :])) / image_height)
min_x = (tf.to_float(tf.reduce_min(new_coords[1, :])) / image_width)
max_y = (tf.to_float(tf.reduce_max(new_coords[0, :])) / image_height)
max_x = (tf.to_float(tf.reduce_max(new_coords[1, :])) / image_width)
(min_y, min_x, max_y, max_x) = _clip_bbox(min_y, min_x, max_y, max_x)
(min_y, min_x, max_y, max_x) = _check_bbox_area(min_y, min_x, max_y, max_x)
return tf.stack([min_y, min_x, max_y, max_x]) | -6,425,782,020,536,974,000 | Shifts the bbox according to how the image was sheared.
Args:
bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)
of type float that represents the normalized coordinates between 0 and 1.
image_height: Int, height of the image.
image_width: Int, height of the image.
level: Float. How much to shear the image.
shear_horizontal: If true then shear in X dimension else shear in
the Y dimension.
Returns:
A tensor of the same shape as bbox, but now with the shifted coordinates. | efficientdet/aug/autoaugment.py | _shear_bbox | datawowio/automl | python | def _shear_bbox(bbox, image_height, image_width, level, shear_horizontal):
'Shifts the bbox according to how the image was sheared.\n\n Args:\n bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)\n of type float that represents the normalized coordinates between 0 and 1.\n image_height: Int, height of the image.\n image_width: Int, height of the image.\n level: Float. How much to shear the image.\n shear_horizontal: If true then shear in X dimension else shear in\n the Y dimension.\n\n Returns:\n A tensor of the same shape as bbox, but now with the shifted coordinates.\n '
(image_height, image_width) = (tf.to_float(image_height), tf.to_float(image_width))
min_y = tf.to_int32((image_height * bbox[0]))
min_x = tf.to_int32((image_width * bbox[1]))
max_y = tf.to_int32((image_height * bbox[2]))
max_x = tf.to_int32((image_width * bbox[3]))
coordinates = tf.stack([[min_y, min_x], [min_y, max_x], [max_y, min_x], [max_y, max_x]])
coordinates = tf.cast(coordinates, tf.float32)
if shear_horizontal:
translation_matrix = tf.stack([[1, 0], [(- level), 1]])
else:
translation_matrix = tf.stack([[1, (- level)], [0, 1]])
translation_matrix = tf.cast(translation_matrix, tf.float32)
new_coords = tf.cast(tf.matmul(translation_matrix, tf.transpose(coordinates)), tf.int32)
min_y = (tf.to_float(tf.reduce_min(new_coords[0, :])) / image_height)
min_x = (tf.to_float(tf.reduce_min(new_coords[1, :])) / image_width)
max_y = (tf.to_float(tf.reduce_max(new_coords[0, :])) / image_height)
max_x = (tf.to_float(tf.reduce_max(new_coords[1, :])) / image_width)
(min_y, min_x, max_y, max_x) = _clip_bbox(min_y, min_x, max_y, max_x)
(min_y, min_x, max_y, max_x) = _check_bbox_area(min_y, min_x, max_y, max_x)
return tf.stack([min_y, min_x, max_y, max_x]) |
def shear_with_bboxes(image, bboxes, level, replace, shear_horizontal):
'Applies Shear Transformation to the image and shifts the bboxes.\n\n Args:\n image: 3D uint8 Tensor.\n bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox\n has 4 elements (min_y, min_x, max_y, max_x) of type float with values\n between [0, 1].\n level: Float. How much to shear the image. This value will be between\n -0.3 to 0.3.\n replace: A one or three value 1D tensor to fill empty pixels.\n shear_horizontal: Boolean. If true then shear in X dimension else shear in\n the Y dimension.\n\n Returns:\n A tuple containing a 3D uint8 Tensor that will be the result of shearing\n image by level. The second element of the tuple is bboxes, where now\n the coordinates will be shifted to reflect the sheared image.\n '
if shear_horizontal:
image = shear_x(image, level, replace)
else:
image = shear_y(image, level, replace)
image_height = tf.shape(image)[0]
image_width = tf.shape(image)[1]
wrapped_shear_bbox = (lambda bbox: _shear_bbox(bbox, image_height, image_width, level, shear_horizontal))
bboxes = tf.map_fn(wrapped_shear_bbox, bboxes)
return (image, bboxes) | -8,922,601,394,061,101,000 | Applies Shear Transformation to the image and shifts the bboxes.
Args:
image: 3D uint8 Tensor.
bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox
has 4 elements (min_y, min_x, max_y, max_x) of type float with values
between [0, 1].
level: Float. How much to shear the image. This value will be between
-0.3 to 0.3.
replace: A one or three value 1D tensor to fill empty pixels.
shear_horizontal: Boolean. If true then shear in X dimension else shear in
the Y dimension.
Returns:
A tuple containing a 3D uint8 Tensor that will be the result of shearing
image by level. The second element of the tuple is bboxes, where now
the coordinates will be shifted to reflect the sheared image. | efficientdet/aug/autoaugment.py | shear_with_bboxes | datawowio/automl | python | def shear_with_bboxes(image, bboxes, level, replace, shear_horizontal):
'Applies Shear Transformation to the image and shifts the bboxes.\n\n Args:\n image: 3D uint8 Tensor.\n bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox\n has 4 elements (min_y, min_x, max_y, max_x) of type float with values\n between [0, 1].\n level: Float. How much to shear the image. This value will be between\n -0.3 to 0.3.\n replace: A one or three value 1D tensor to fill empty pixels.\n shear_horizontal: Boolean. If true then shear in X dimension else shear in\n the Y dimension.\n\n Returns:\n A tuple containing a 3D uint8 Tensor that will be the result of shearing\n image by level. The second element of the tuple is bboxes, where now\n the coordinates will be shifted to reflect the sheared image.\n '
if shear_horizontal:
image = shear_x(image, level, replace)
else:
image = shear_y(image, level, replace)
image_height = tf.shape(image)[0]
image_width = tf.shape(image)[1]
wrapped_shear_bbox = (lambda bbox: _shear_bbox(bbox, image_height, image_width, level, shear_horizontal))
bboxes = tf.map_fn(wrapped_shear_bbox, bboxes)
return (image, bboxes) |
def autocontrast(image):
'Implements Autocontrast function from PIL using TF ops.\n\n Args:\n image: A 3D uint8 tensor.\n\n Returns:\n The image after it has had autocontrast applied to it and will be of type\n uint8.\n '
def scale_channel(image):
'Scale the 2D image using the autocontrast rule.'
lo = tf.to_float(tf.reduce_min(image))
hi = tf.to_float(tf.reduce_max(image))
def scale_values(im):
scale = (255.0 / (hi - lo))
offset = ((- lo) * scale)
im = ((tf.to_float(im) * scale) + offset)
im = tf.clip_by_value(im, 0.0, 255.0)
return tf.cast(im, tf.uint8)
result = tf.cond((hi > lo), (lambda : scale_values(image)), (lambda : image))
return result
s1 = scale_channel(image[:, :, 0])
s2 = scale_channel(image[:, :, 1])
s3 = scale_channel(image[:, :, 2])
image = tf.stack([s1, s2, s3], 2)
return image | 303,571,217,608,186,900 | Implements Autocontrast function from PIL using TF ops.
Args:
image: A 3D uint8 tensor.
Returns:
The image after it has had autocontrast applied to it and will be of type
uint8. | efficientdet/aug/autoaugment.py | autocontrast | datawowio/automl | python | def autocontrast(image):
'Implements Autocontrast function from PIL using TF ops.\n\n Args:\n image: A 3D uint8 tensor.\n\n Returns:\n The image after it has had autocontrast applied to it and will be of type\n uint8.\n '
def scale_channel(image):
'Scale the 2D image using the autocontrast rule.'
lo = tf.to_float(tf.reduce_min(image))
hi = tf.to_float(tf.reduce_max(image))
def scale_values(im):
scale = (255.0 / (hi - lo))
offset = ((- lo) * scale)
im = ((tf.to_float(im) * scale) + offset)
im = tf.clip_by_value(im, 0.0, 255.0)
return tf.cast(im, tf.uint8)
result = tf.cond((hi > lo), (lambda : scale_values(image)), (lambda : image))
return result
s1 = scale_channel(image[:, :, 0])
s2 = scale_channel(image[:, :, 1])
s3 = scale_channel(image[:, :, 2])
image = tf.stack([s1, s2, s3], 2)
return image |
def sharpness(image, factor):
'Implements Sharpness function from PIL using TF ops.'
orig_image = image
image = tf.cast(image, tf.float32)
image = tf.expand_dims(image, 0)
kernel = (tf.constant([[1, 1, 1], [1, 5, 1], [1, 1, 1]], dtype=tf.float32, shape=[3, 3, 1, 1]) / 13.0)
kernel = tf.tile(kernel, [1, 1, 3, 1])
strides = [1, 1, 1, 1]
with tf.device('/cpu:0'):
degenerate = tf.nn.depthwise_conv2d(image, kernel, strides, padding='VALID', rate=[1, 1])
degenerate = tf.clip_by_value(degenerate, 0.0, 255.0)
degenerate = tf.squeeze(tf.cast(degenerate, tf.uint8), [0])
mask = tf.ones_like(degenerate)
padded_mask = tf.pad(mask, [[1, 1], [1, 1], [0, 0]])
padded_degenerate = tf.pad(degenerate, [[1, 1], [1, 1], [0, 0]])
result = tf.where(tf.equal(padded_mask, 1), padded_degenerate, orig_image)
return blend(result, orig_image, factor) | -1,232,677,706,748,177,200 | Implements Sharpness function from PIL using TF ops. | efficientdet/aug/autoaugment.py | sharpness | datawowio/automl | python | def sharpness(image, factor):
orig_image = image
image = tf.cast(image, tf.float32)
image = tf.expand_dims(image, 0)
kernel = (tf.constant([[1, 1, 1], [1, 5, 1], [1, 1, 1]], dtype=tf.float32, shape=[3, 3, 1, 1]) / 13.0)
kernel = tf.tile(kernel, [1, 1, 3, 1])
strides = [1, 1, 1, 1]
with tf.device('/cpu:0'):
degenerate = tf.nn.depthwise_conv2d(image, kernel, strides, padding='VALID', rate=[1, 1])
degenerate = tf.clip_by_value(degenerate, 0.0, 255.0)
degenerate = tf.squeeze(tf.cast(degenerate, tf.uint8), [0])
mask = tf.ones_like(degenerate)
padded_mask = tf.pad(mask, [[1, 1], [1, 1], [0, 0]])
padded_degenerate = tf.pad(degenerate, [[1, 1], [1, 1], [0, 0]])
result = tf.where(tf.equal(padded_mask, 1), padded_degenerate, orig_image)
return blend(result, orig_image, factor) |
def equalize(image):
'Implements Equalize function from PIL using TF ops.'
def scale_channel(im, c):
'Scale the data in the channel to implement equalize.'
im = tf.cast(im[:, :, c], tf.int32)
histo = tf.histogram_fixed_width(im, [0, 255], nbins=256)
nonzero = tf.where(tf.not_equal(histo, 0))
nonzero_histo = tf.reshape(tf.gather(histo, nonzero), [(- 1)])
step = ((tf.reduce_sum(nonzero_histo) - nonzero_histo[(- 1)]) // 255)
def build_lut(histo, step):
lut = ((tf.cumsum(histo) + (step // 2)) // step)
lut = tf.concat([[0], lut[:(- 1)]], 0)
return tf.clip_by_value(lut, 0, 255)
result = tf.cond(tf.equal(step, 0), (lambda : im), (lambda : tf.gather(build_lut(histo, step), im)))
return tf.cast(result, tf.uint8)
s1 = scale_channel(image, 0)
s2 = scale_channel(image, 1)
s3 = scale_channel(image, 2)
image = tf.stack([s1, s2, s3], 2)
return image | -4,360,158,787,895,066,600 | Implements Equalize function from PIL using TF ops. | efficientdet/aug/autoaugment.py | equalize | datawowio/automl | python | def equalize(image):
def scale_channel(im, c):
'Scale the data in the channel to implement equalize.'
im = tf.cast(im[:, :, c], tf.int32)
histo = tf.histogram_fixed_width(im, [0, 255], nbins=256)
nonzero = tf.where(tf.not_equal(histo, 0))
nonzero_histo = tf.reshape(tf.gather(histo, nonzero), [(- 1)])
step = ((tf.reduce_sum(nonzero_histo) - nonzero_histo[(- 1)]) // 255)
def build_lut(histo, step):
lut = ((tf.cumsum(histo) + (step // 2)) // step)
lut = tf.concat([[0], lut[:(- 1)]], 0)
return tf.clip_by_value(lut, 0, 255)
result = tf.cond(tf.equal(step, 0), (lambda : im), (lambda : tf.gather(build_lut(histo, step), im)))
return tf.cast(result, tf.uint8)
s1 = scale_channel(image, 0)
s2 = scale_channel(image, 1)
s3 = scale_channel(image, 2)
image = tf.stack([s1, s2, s3], 2)
return image |
def wrap(image):
"Returns 'image' with an extra channel set to all 1s."
shape = tf.shape(image)
extended_channel = tf.ones([shape[0], shape[1], 1], image.dtype)
extended = tf.concat([image, extended_channel], 2)
return extended | -2,054,740,842,410,237,000 | Returns 'image' with an extra channel set to all 1s. | efficientdet/aug/autoaugment.py | wrap | datawowio/automl | python | def wrap(image):
shape = tf.shape(image)
extended_channel = tf.ones([shape[0], shape[1], 1], image.dtype)
extended = tf.concat([image, extended_channel], 2)
return extended |
def unwrap(image, replace):
"Unwraps an image produced by wrap.\n\n Where there is a 0 in the last channel for every spatial position,\n the rest of the three channels in that spatial dimension are grayed\n (set to 128). Operations like translate and shear on a wrapped\n Tensor will leave 0s in empty locations. Some transformations look\n at the intensity of values to do preprocessing, and we want these\n empty pixels to assume the 'average' value, rather than pure black.\n\n\n Args:\n image: A 3D Image Tensor with 4 channels.\n replace: A one or three value 1D tensor to fill empty pixels.\n\n Returns:\n image: A 3D image Tensor with 3 channels.\n "
image_shape = tf.shape(image)
flattened_image = tf.reshape(image, [(- 1), image_shape[2]])
alpha_channel = flattened_image[:, 3]
replace = tf.concat([replace, tf.ones([1], image.dtype)], 0)
flattened_image = tf.where(tf.equal(alpha_channel, 0), (tf.ones_like(flattened_image, dtype=image.dtype) * replace), flattened_image)
image = tf.reshape(flattened_image, image_shape)
image = tf.slice(image, [0, 0, 0], [image_shape[0], image_shape[1], 3])
return image | 6,263,443,170,076,591,000 | Unwraps an image produced by wrap.
Where there is a 0 in the last channel for every spatial position,
the rest of the three channels in that spatial dimension are grayed
(set to 128). Operations like translate and shear on a wrapped
Tensor will leave 0s in empty locations. Some transformations look
at the intensity of values to do preprocessing, and we want these
empty pixels to assume the 'average' value, rather than pure black.
Args:
image: A 3D Image Tensor with 4 channels.
replace: A one or three value 1D tensor to fill empty pixels.
Returns:
image: A 3D image Tensor with 3 channels. | efficientdet/aug/autoaugment.py | unwrap | datawowio/automl | python | def unwrap(image, replace):
"Unwraps an image produced by wrap.\n\n Where there is a 0 in the last channel for every spatial position,\n the rest of the three channels in that spatial dimension are grayed\n (set to 128). Operations like translate and shear on a wrapped\n Tensor will leave 0s in empty locations. Some transformations look\n at the intensity of values to do preprocessing, and we want these\n empty pixels to assume the 'average' value, rather than pure black.\n\n\n Args:\n image: A 3D Image Tensor with 4 channels.\n replace: A one or three value 1D tensor to fill empty pixels.\n\n Returns:\n image: A 3D image Tensor with 3 channels.\n "
image_shape = tf.shape(image)
flattened_image = tf.reshape(image, [(- 1), image_shape[2]])
alpha_channel = flattened_image[:, 3]
replace = tf.concat([replace, tf.ones([1], image.dtype)], 0)
flattened_image = tf.where(tf.equal(alpha_channel, 0), (tf.ones_like(flattened_image, dtype=image.dtype) * replace), flattened_image)
image = tf.reshape(flattened_image, image_shape)
image = tf.slice(image, [0, 0, 0], [image_shape[0], image_shape[1], 3])
return image |
def _cutout_inside_bbox(image, bbox, pad_fraction):
'Generates cutout mask and the mean pixel value of the bbox.\n\n First a location is randomly chosen within the image as the center where the\n cutout mask will be applied. Note this can be towards the boundaries of the\n image, so the full cutout mask may not be applied.\n\n Args:\n image: 3D uint8 Tensor.\n bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)\n of type float that represents the normalized coordinates between 0 and 1.\n pad_fraction: Float that specifies how large the cutout mask should be in\n in reference to the size of the original bbox. If pad_fraction is 0.25,\n then the cutout mask will be of shape\n (0.25 * bbox height, 0.25 * bbox width).\n\n Returns:\n A tuple. Fist element is a tensor of the same shape as image where each\n element is either a 1 or 0 that is used to determine where the image\n will have cutout applied. The second element is the mean of the pixels\n in the image where the bbox is located.\n '
image_height = tf.maximum(tf.shape(image)[0], 10)
image_width = tf.maximum(tf.shape(image)[1], 10)
bbox = tf.squeeze(bbox)
min_y = tf.to_int32((tf.to_float(image_height) * bbox[0]))
min_x = tf.to_int32((tf.to_float(image_width) * bbox[1]))
max_y = tf.to_int32((tf.to_float(image_height) * bbox[2]))
max_x = tf.to_int32((tf.to_float(image_width) * bbox[3]))
mean = tf.reduce_mean(image[min_y:(max_y + 1), min_x:(max_x + 1)], reduction_indices=[0, 1])
box_height = ((max_y - min_y) + 1)
box_width = ((max_x - min_x) + 1)
pad_size_height = tf.to_int32((pad_fraction * (box_height / 2)))
pad_size_width = tf.to_int32((pad_fraction * (box_width / 2)))
cutout_center_height = tf.random_uniform(shape=[], minval=min_y, maxval=(max_y + 1), dtype=tf.int32)
cutout_center_width = tf.random_uniform(shape=[], minval=min_x, maxval=(max_x + 1), dtype=tf.int32)
lower_pad = tf.maximum(0, (cutout_center_height - pad_size_height))
upper_pad = tf.maximum(0, ((image_height - cutout_center_height) - pad_size_height))
left_pad = tf.maximum(0, (cutout_center_width - pad_size_width))
right_pad = tf.maximum(0, ((image_width - cutout_center_width) - pad_size_width))
cutout_shape = [(image_height - (lower_pad + upper_pad)), (image_width - (left_pad + right_pad))]
padding_dims = [[lower_pad, upper_pad], [left_pad, right_pad]]
mask = tf.pad(tf.zeros(cutout_shape, dtype=image.dtype), padding_dims, constant_values=1)
mask = tf.expand_dims(mask, 2)
mask = tf.tile(mask, [1, 1, 3])
return (mask, mean) | -8,068,290,216,123,599,000 | Generates cutout mask and the mean pixel value of the bbox.
First a location is randomly chosen within the image as the center where the
cutout mask will be applied. Note this can be towards the boundaries of the
image, so the full cutout mask may not be applied.
Args:
image: 3D uint8 Tensor.
bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)
of type float that represents the normalized coordinates between 0 and 1.
pad_fraction: Float that specifies how large the cutout mask should be in
in reference to the size of the original bbox. If pad_fraction is 0.25,
then the cutout mask will be of shape
(0.25 * bbox height, 0.25 * bbox width).
Returns:
A tuple. Fist element is a tensor of the same shape as image where each
element is either a 1 or 0 that is used to determine where the image
will have cutout applied. The second element is the mean of the pixels
in the image where the bbox is located. | efficientdet/aug/autoaugment.py | _cutout_inside_bbox | datawowio/automl | python | def _cutout_inside_bbox(image, bbox, pad_fraction):
'Generates cutout mask and the mean pixel value of the bbox.\n\n First a location is randomly chosen within the image as the center where the\n cutout mask will be applied. Note this can be towards the boundaries of the\n image, so the full cutout mask may not be applied.\n\n Args:\n image: 3D uint8 Tensor.\n bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)\n of type float that represents the normalized coordinates between 0 and 1.\n pad_fraction: Float that specifies how large the cutout mask should be in\n in reference to the size of the original bbox. If pad_fraction is 0.25,\n then the cutout mask will be of shape\n (0.25 * bbox height, 0.25 * bbox width).\n\n Returns:\n A tuple. Fist element is a tensor of the same shape as image where each\n element is either a 1 or 0 that is used to determine where the image\n will have cutout applied. The second element is the mean of the pixels\n in the image where the bbox is located.\n '
image_height = tf.maximum(tf.shape(image)[0], 10)
image_width = tf.maximum(tf.shape(image)[1], 10)
bbox = tf.squeeze(bbox)
min_y = tf.to_int32((tf.to_float(image_height) * bbox[0]))
min_x = tf.to_int32((tf.to_float(image_width) * bbox[1]))
max_y = tf.to_int32((tf.to_float(image_height) * bbox[2]))
max_x = tf.to_int32((tf.to_float(image_width) * bbox[3]))
mean = tf.reduce_mean(image[min_y:(max_y + 1), min_x:(max_x + 1)], reduction_indices=[0, 1])
box_height = ((max_y - min_y) + 1)
box_width = ((max_x - min_x) + 1)
pad_size_height = tf.to_int32((pad_fraction * (box_height / 2)))
pad_size_width = tf.to_int32((pad_fraction * (box_width / 2)))
cutout_center_height = tf.random_uniform(shape=[], minval=min_y, maxval=(max_y + 1), dtype=tf.int32)
cutout_center_width = tf.random_uniform(shape=[], minval=min_x, maxval=(max_x + 1), dtype=tf.int32)
lower_pad = tf.maximum(0, (cutout_center_height - pad_size_height))
upper_pad = tf.maximum(0, ((image_height - cutout_center_height) - pad_size_height))
left_pad = tf.maximum(0, (cutout_center_width - pad_size_width))
right_pad = tf.maximum(0, ((image_width - cutout_center_width) - pad_size_width))
cutout_shape = [(image_height - (lower_pad + upper_pad)), (image_width - (left_pad + right_pad))]
padding_dims = [[lower_pad, upper_pad], [left_pad, right_pad]]
mask = tf.pad(tf.zeros(cutout_shape, dtype=image.dtype), padding_dims, constant_values=1)
mask = tf.expand_dims(mask, 2)
mask = tf.tile(mask, [1, 1, 3])
return (mask, mean) |
def bbox_cutout(image, bboxes, pad_fraction, replace_with_mean):
'Applies cutout to the image according to bbox information.\n\n This is a cutout variant that using bbox information to make more informed\n decisions on where to place the cutout mask.\n\n Args:\n image: 3D uint8 Tensor.\n bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox\n has 4 elements (min_y, min_x, max_y, max_x) of type float with values\n between [0, 1].\n pad_fraction: Float that specifies how large the cutout mask should be in\n in reference to the size of the original bbox. If pad_fraction is 0.25,\n then the cutout mask will be of shape\n (0.25 * bbox height, 0.25 * bbox width).\n replace_with_mean: Boolean that specified what value should be filled in\n where the cutout mask is applied. Since the incoming image will be of\n uint8 and will not have had any mean normalization applied, by default\n we set the value to be 128. If replace_with_mean is True then we find\n the mean pixel values across the channel dimension and use those to fill\n in where the cutout mask is applied.\n\n Returns:\n A tuple. First element is a tensor of the same shape as image that has\n cutout applied to it. Second element is the bboxes that were passed in\n that will be unchanged.\n '
def apply_bbox_cutout(image, bboxes, pad_fraction):
'Applies cutout to a single bounding box within image.'
random_index = tf.random_uniform(shape=[], maxval=tf.shape(bboxes)[0], dtype=tf.int32)
chosen_bbox = tf.gather(bboxes, random_index)
(mask, mean) = _cutout_inside_bbox(image, chosen_bbox, pad_fraction)
replace = (mean if replace_with_mean else 128)
image = tf.where(tf.equal(mask, 0), tf.cast((tf.ones_like(image, dtype=image.dtype) * replace), dtype=image.dtype), image)
return image
image = tf.cond(tf.equal(tf.shape(bboxes)[0], 0), (lambda : image), (lambda : apply_bbox_cutout(image, bboxes, pad_fraction)))
return (image, bboxes) | 3,325,208,541,111,828,000 | Applies cutout to the image according to bbox information.
This is a cutout variant that using bbox information to make more informed
decisions on where to place the cutout mask.
Args:
image: 3D uint8 Tensor.
bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox
has 4 elements (min_y, min_x, max_y, max_x) of type float with values
between [0, 1].
pad_fraction: Float that specifies how large the cutout mask should be in
in reference to the size of the original bbox. If pad_fraction is 0.25,
then the cutout mask will be of shape
(0.25 * bbox height, 0.25 * bbox width).
replace_with_mean: Boolean that specified what value should be filled in
where the cutout mask is applied. Since the incoming image will be of
uint8 and will not have had any mean normalization applied, by default
we set the value to be 128. If replace_with_mean is True then we find
the mean pixel values across the channel dimension and use those to fill
in where the cutout mask is applied.
Returns:
A tuple. First element is a tensor of the same shape as image that has
cutout applied to it. Second element is the bboxes that were passed in
that will be unchanged. | efficientdet/aug/autoaugment.py | bbox_cutout | datawowio/automl | python | def bbox_cutout(image, bboxes, pad_fraction, replace_with_mean):
'Applies cutout to the image according to bbox information.\n\n This is a cutout variant that using bbox information to make more informed\n decisions on where to place the cutout mask.\n\n Args:\n image: 3D uint8 Tensor.\n bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox\n has 4 elements (min_y, min_x, max_y, max_x) of type float with values\n between [0, 1].\n pad_fraction: Float that specifies how large the cutout mask should be in\n in reference to the size of the original bbox. If pad_fraction is 0.25,\n then the cutout mask will be of shape\n (0.25 * bbox height, 0.25 * bbox width).\n replace_with_mean: Boolean that specified what value should be filled in\n where the cutout mask is applied. Since the incoming image will be of\n uint8 and will not have had any mean normalization applied, by default\n we set the value to be 128. If replace_with_mean is True then we find\n the mean pixel values across the channel dimension and use those to fill\n in where the cutout mask is applied.\n\n Returns:\n A tuple. First element is a tensor of the same shape as image that has\n cutout applied to it. Second element is the bboxes that were passed in\n that will be unchanged.\n '
def apply_bbox_cutout(image, bboxes, pad_fraction):
'Applies cutout to a single bounding box within image.'
random_index = tf.random_uniform(shape=[], maxval=tf.shape(bboxes)[0], dtype=tf.int32)
chosen_bbox = tf.gather(bboxes, random_index)
(mask, mean) = _cutout_inside_bbox(image, chosen_bbox, pad_fraction)
replace = (mean if replace_with_mean else 128)
image = tf.where(tf.equal(mask, 0), tf.cast((tf.ones_like(image, dtype=image.dtype) * replace), dtype=image.dtype), image)
return image
image = tf.cond(tf.equal(tf.shape(bboxes)[0], 0), (lambda : image), (lambda : apply_bbox_cutout(image, bboxes, pad_fraction)))
return (image, bboxes) |
def _randomly_negate_tensor(tensor):
'With 50% prob turn the tensor negative.'
should_flip = tf.cast(tf.floor((tf.random_uniform([]) + 0.5)), tf.bool)
final_tensor = tf.cond(should_flip, (lambda : tensor), (lambda : (- tensor)))
return final_tensor | 7,650,776,648,965,303,000 | With 50% prob turn the tensor negative. | efficientdet/aug/autoaugment.py | _randomly_negate_tensor | datawowio/automl | python | def _randomly_negate_tensor(tensor):
should_flip = tf.cast(tf.floor((tf.random_uniform([]) + 0.5)), tf.bool)
final_tensor = tf.cond(should_flip, (lambda : tensor), (lambda : (- tensor)))
return final_tensor |
def _shrink_level_to_arg(level):
'Converts level to ratio by which we shrink the image content.'
if (level == 0):
return (1.0,)
level = ((2.0 / (_MAX_LEVEL / level)) + 0.9)
return (level,) | 9,177,563,595,245,319,000 | Converts level to ratio by which we shrink the image content. | efficientdet/aug/autoaugment.py | _shrink_level_to_arg | datawowio/automl | python | def _shrink_level_to_arg(level):
if (level == 0):
return (1.0,)
level = ((2.0 / (_MAX_LEVEL / level)) + 0.9)
return (level,) |
def bbox_wrapper(func):
'Adds a bboxes function argument to func and returns unchanged bboxes.'
def wrapper(images, bboxes, *args, **kwargs):
return (func(images, *args, **kwargs), bboxes)
return wrapper | 7,986,334,951,161,487,000 | Adds a bboxes function argument to func and returns unchanged bboxes. | efficientdet/aug/autoaugment.py | bbox_wrapper | datawowio/automl | python | def bbox_wrapper(func):
def wrapper(images, bboxes, *args, **kwargs):
return (func(images, *args, **kwargs), bboxes)
return wrapper |
def _parse_policy_info(name, prob, level, replace_value, augmentation_hparams):
'Return the function that corresponds to `name` and update `level` param.'
func = NAME_TO_FUNC[name]
args = level_to_arg(augmentation_hparams)[name](level)
if ('prob' in inspect.getfullargspec(func)[0]):
args = tuple(([prob] + list(args)))
if ('replace' in inspect.getfullargspec(func)[0]):
assert ('replace' == inspect.getfullargspec(func)[0][(- 1)])
args = tuple((list(args) + [replace_value]))
if ('bboxes' not in inspect.getfullargspec(func)[0]):
func = bbox_wrapper(func)
return (func, prob, args) | 1,299,395,002,175,213,300 | Return the function that corresponds to `name` and update `level` param. | efficientdet/aug/autoaugment.py | _parse_policy_info | datawowio/automl | python | def _parse_policy_info(name, prob, level, replace_value, augmentation_hparams):
func = NAME_TO_FUNC[name]
args = level_to_arg(augmentation_hparams)[name](level)
if ('prob' in inspect.getfullargspec(func)[0]):
args = tuple(([prob] + list(args)))
if ('replace' in inspect.getfullargspec(func)[0]):
assert ('replace' == inspect.getfullargspec(func)[0][(- 1)])
args = tuple((list(args) + [replace_value]))
if ('bboxes' not in inspect.getfullargspec(func)[0]):
func = bbox_wrapper(func)
return (func, prob, args) |
def _apply_func_with_prob(func, image, args, prob, bboxes):
'Apply `func` to image w/ `args` as input with probability `prob`.'
assert isinstance(args, tuple)
assert ('bboxes' == inspect.getfullargspec(func)[0][1])
if ('prob' in inspect.getfullargspec(func)[0]):
prob = 1.0
should_apply_op = tf.cast(tf.floor((tf.random_uniform([], dtype=tf.float32) + prob)), tf.bool)
(augmented_image, augmented_bboxes) = tf.cond(should_apply_op, (lambda : func(image, bboxes, *args)), (lambda : (image, bboxes)))
return (augmented_image, augmented_bboxes) | -935,833,796,455,203,700 | Apply `func` to image w/ `args` as input with probability `prob`. | efficientdet/aug/autoaugment.py | _apply_func_with_prob | datawowio/automl | python | def _apply_func_with_prob(func, image, args, prob, bboxes):
assert isinstance(args, tuple)
assert ('bboxes' == inspect.getfullargspec(func)[0][1])
if ('prob' in inspect.getfullargspec(func)[0]):
prob = 1.0
should_apply_op = tf.cast(tf.floor((tf.random_uniform([], dtype=tf.float32) + prob)), tf.bool)
(augmented_image, augmented_bboxes) = tf.cond(should_apply_op, (lambda : func(image, bboxes, *args)), (lambda : (image, bboxes)))
return (augmented_image, augmented_bboxes) |
def select_and_apply_random_policy(policies, image, bboxes):
'Select a random policy from `policies` and apply it to `image`.'
policy_to_select = tf.random_uniform([], maxval=len(policies), dtype=tf.int32)
for (i, policy) in enumerate(policies):
(image, bboxes) = tf.cond(tf.equal(i, policy_to_select), (lambda selected_policy=policy: selected_policy(image, bboxes)), (lambda : (image, bboxes)))
return (image, bboxes) | -2,167,437,932,029,373,700 | Select a random policy from `policies` and apply it to `image`. | efficientdet/aug/autoaugment.py | select_and_apply_random_policy | datawowio/automl | python | def select_and_apply_random_policy(policies, image, bboxes):
policy_to_select = tf.random_uniform([], maxval=len(policies), dtype=tf.int32)
for (i, policy) in enumerate(policies):
(image, bboxes) = tf.cond(tf.equal(i, policy_to_select), (lambda selected_policy=policy: selected_policy(image, bboxes)), (lambda : (image, bboxes)))
return (image, bboxes) |
def build_and_apply_nas_policy(policies, image, bboxes, augmentation_hparams):
'Build a policy from the given policies passed in and apply to image.\n\n Args:\n policies: list of lists of tuples in the form `(func, prob, level)`, `func`\n is a string name of the augmentation function, `prob` is the probability\n of applying the `func` operation, `level` is the input argument for\n `func`.\n image: tf.Tensor that the resulting policy will be applied to.\n bboxes: tf.Tensor of shape [N, 4] representing ground truth boxes that are\n normalized between [0, 1].\n augmentation_hparams: Hparams associated with the NAS learned policy.\n\n Returns:\n A version of image that now has data augmentation applied to it based on\n the `policies` pass into the function. Additionally, returns bboxes if\n a value for them is passed in that is not None\n '
replace_value = [128, 128, 128]
tf_policies = []
for policy in policies:
tf_policy = []
for policy_info in policy:
policy_info = (list(policy_info) + [replace_value, augmentation_hparams])
tf_policy.append(_parse_policy_info(*policy_info))
def make_final_policy(tf_policy_):
def final_policy(image_, bboxes_):
for (func, prob, args) in tf_policy_:
(image_, bboxes_) = _apply_func_with_prob(func, image_, args, prob, bboxes_)
return (image_, bboxes_)
return final_policy
tf_policies.append(make_final_policy(tf_policy))
(augmented_images, augmented_bboxes) = select_and_apply_random_policy(tf_policies, image, bboxes)
return (augmented_images, augmented_bboxes) | -5,391,226,156,041,492,000 | Build a policy from the given policies passed in and apply to image.
Args:
policies: list of lists of tuples in the form `(func, prob, level)`, `func`
is a string name of the augmentation function, `prob` is the probability
of applying the `func` operation, `level` is the input argument for
`func`.
image: tf.Tensor that the resulting policy will be applied to.
bboxes: tf.Tensor of shape [N, 4] representing ground truth boxes that are
normalized between [0, 1].
augmentation_hparams: Hparams associated with the NAS learned policy.
Returns:
A version of image that now has data augmentation applied to it based on
the `policies` pass into the function. Additionally, returns bboxes if
a value for them is passed in that is not None | efficientdet/aug/autoaugment.py | build_and_apply_nas_policy | datawowio/automl | python | def build_and_apply_nas_policy(policies, image, bboxes, augmentation_hparams):
'Build a policy from the given policies passed in and apply to image.\n\n Args:\n policies: list of lists of tuples in the form `(func, prob, level)`, `func`\n is a string name of the augmentation function, `prob` is the probability\n of applying the `func` operation, `level` is the input argument for\n `func`.\n image: tf.Tensor that the resulting policy will be applied to.\n bboxes: tf.Tensor of shape [N, 4] representing ground truth boxes that are\n normalized between [0, 1].\n augmentation_hparams: Hparams associated with the NAS learned policy.\n\n Returns:\n A version of image that now has data augmentation applied to it based on\n the `policies` pass into the function. Additionally, returns bboxes if\n a value for them is passed in that is not None\n '
replace_value = [128, 128, 128]
tf_policies = []
for policy in policies:
tf_policy = []
for policy_info in policy:
policy_info = (list(policy_info) + [replace_value, augmentation_hparams])
tf_policy.append(_parse_policy_info(*policy_info))
def make_final_policy(tf_policy_):
def final_policy(image_, bboxes_):
for (func, prob, args) in tf_policy_:
(image_, bboxes_) = _apply_func_with_prob(func, image_, args, prob, bboxes_)
return (image_, bboxes_)
return final_policy
tf_policies.append(make_final_policy(tf_policy))
(augmented_images, augmented_bboxes) = select_and_apply_random_policy(tf_policies, image, bboxes)
return (augmented_images, augmented_bboxes) |
@tf.autograph.experimental.do_not_convert
def distort_image_with_autoaugment(image, bboxes, augmentation_name):
'Applies the AutoAugment policy to `image` and `bboxes`.\n\n Args:\n image: `Tensor` of shape [height, width, 3] representing an image.\n bboxes: `Tensor` of shape [N, 4] representing ground truth boxes that are\n normalized between [0, 1].\n augmentation_name: The name of the AutoAugment policy to use. The available\n options are `v0`, `v1`, `v2`, `v3` and `test`. `v0` is the policy used for\n all of the results in the paper and was found to achieve the best results\n on the COCO dataset. `v1`, `v2` and `v3` are additional good policies\n found on the COCO dataset that have slight variation in what operations\n were used during the search procedure along with how many operations are\n applied in parallel to a single image (2 vs 3).\n\n Returns:\n A tuple containing the augmented versions of `image` and `bboxes`.\n '
logging.info('Using autoaugmention policy: %s', augmentation_name)
available_policies = {'v0': policy_v0, 'v1': policy_v1, 'v2': policy_v2, 'v3': policy_v3, 'test': policy_vtest}
if (augmentation_name not in available_policies):
raise ValueError('Invalid augmentation_name: {}'.format(augmentation_name))
policy = available_policies[augmentation_name]()
augmentation_hparams = hparams_config.Config(dict(cutout_max_pad_fraction=0.75, cutout_bbox_replace_with_mean=False, cutout_const=100, translate_const=250, cutout_bbox_const=50, translate_bbox_const=120))
return build_and_apply_nas_policy(policy, image, bboxes, augmentation_hparams) | 6,681,142,781,319,894,000 | Applies the AutoAugment policy to `image` and `bboxes`.
Args:
image: `Tensor` of shape [height, width, 3] representing an image.
bboxes: `Tensor` of shape [N, 4] representing ground truth boxes that are
normalized between [0, 1].
augmentation_name: The name of the AutoAugment policy to use. The available
options are `v0`, `v1`, `v2`, `v3` and `test`. `v0` is the policy used for
all of the results in the paper and was found to achieve the best results
on the COCO dataset. `v1`, `v2` and `v3` are additional good policies
found on the COCO dataset that have slight variation in what operations
were used during the search procedure along with how many operations are
applied in parallel to a single image (2 vs 3).
Returns:
A tuple containing the augmented versions of `image` and `bboxes`. | efficientdet/aug/autoaugment.py | distort_image_with_autoaugment | datawowio/automl | python | @tf.autograph.experimental.do_not_convert
def distort_image_with_autoaugment(image, bboxes, augmentation_name):
'Applies the AutoAugment policy to `image` and `bboxes`.\n\n Args:\n image: `Tensor` of shape [height, width, 3] representing an image.\n bboxes: `Tensor` of shape [N, 4] representing ground truth boxes that are\n normalized between [0, 1].\n augmentation_name: The name of the AutoAugment policy to use. The available\n options are `v0`, `v1`, `v2`, `v3` and `test`. `v0` is the policy used for\n all of the results in the paper and was found to achieve the best results\n on the COCO dataset. `v1`, `v2` and `v3` are additional good policies\n found on the COCO dataset that have slight variation in what operations\n were used during the search procedure along with how many operations are\n applied in parallel to a single image (2 vs 3).\n\n Returns:\n A tuple containing the augmented versions of `image` and `bboxes`.\n '
logging.info('Using autoaugmention policy: %s', augmentation_name)
available_policies = {'v0': policy_v0, 'v1': policy_v1, 'v2': policy_v2, 'v3': policy_v3, 'test': policy_vtest}
if (augmentation_name not in available_policies):
raise ValueError('Invalid augmentation_name: {}'.format(augmentation_name))
policy = available_policies[augmentation_name]()
augmentation_hparams = hparams_config.Config(dict(cutout_max_pad_fraction=0.75, cutout_bbox_replace_with_mean=False, cutout_const=100, translate_const=250, cutout_bbox_const=50, translate_bbox_const=120))
return build_and_apply_nas_policy(policy, image, bboxes, augmentation_hparams) |
def distort_image_with_randaugment(image, bboxes, num_layers, magnitude):
'Applies the RandAugment to `image` and `bboxes`.'
replace_value = [128, 128, 128]
tf.logging.info('Using RandAugment.')
augmentation_hparams = hparams_config.Config(dict(cutout_max_pad_fraction=0.75, cutout_bbox_replace_with_mean=False, cutout_const=100, translate_const=250, cutout_bbox_const=50, translate_bbox_const=120))
available_ops = ['Equalize', 'Solarize', 'Color', 'Cutout', 'SolarizeAdd', 'TranslateX_BBox', 'TranslateY_BBox', 'ShearX_BBox', 'ShearY_BBox', 'Rotate_BBox']
if (bboxes is None):
bboxes = tf.constant(0.0)
for layer_num in range(num_layers):
op_to_select = tf.random_uniform([], maxval=len(available_ops), dtype=tf.int32)
random_magnitude = float(magnitude)
with tf.name_scope('randaug_layer_{}'.format(layer_num)):
for (i, op_name) in enumerate(available_ops):
prob = tf.random_uniform([], minval=0.2, maxval=0.8, dtype=tf.float32)
(func, _, args) = _parse_policy_info(op_name, prob, random_magnitude, replace_value, augmentation_hparams)
(image, bboxes) = tf.cond(tf.equal(i, op_to_select), (lambda fn=func, fn_args=args: fn(image, bboxes, *fn_args)), (lambda : (image, bboxes)))
return (image, bboxes) | 6,479,833,031,204,732,000 | Applies the RandAugment to `image` and `bboxes`. | efficientdet/aug/autoaugment.py | distort_image_with_randaugment | datawowio/automl | python | def distort_image_with_randaugment(image, bboxes, num_layers, magnitude):
replace_value = [128, 128, 128]
tf.logging.info('Using RandAugment.')
augmentation_hparams = hparams_config.Config(dict(cutout_max_pad_fraction=0.75, cutout_bbox_replace_with_mean=False, cutout_const=100, translate_const=250, cutout_bbox_const=50, translate_bbox_const=120))
available_ops = ['Equalize', 'Solarize', 'Color', 'Cutout', 'SolarizeAdd', 'TranslateX_BBox', 'TranslateY_BBox', 'ShearX_BBox', 'ShearY_BBox', 'Rotate_BBox']
if (bboxes is None):
bboxes = tf.constant(0.0)
for layer_num in range(num_layers):
op_to_select = tf.random_uniform([], maxval=len(available_ops), dtype=tf.int32)
random_magnitude = float(magnitude)
with tf.name_scope('randaug_layer_{}'.format(layer_num)):
for (i, op_name) in enumerate(available_ops):
prob = tf.random_uniform([], minval=0.2, maxval=0.8, dtype=tf.float32)
(func, _, args) = _parse_policy_info(op_name, prob, random_magnitude, replace_value, augmentation_hparams)
(image, bboxes) = tf.cond(tf.equal(i, op_to_select), (lambda fn=func, fn_args=args: fn(image, bboxes, *fn_args)), (lambda : (image, bboxes)))
return (image, bboxes) |
def mask_and_add_image(min_y_, min_x_, max_y_, max_x_, mask, content_tensor, image_):
'Applies mask to bbox region in image then adds content_tensor to it.'
mask = tf.pad(mask, [[min_y_, ((image_height - 1) - max_y_)], [min_x_, ((image_width - 1) - max_x_)], [0, 0]], constant_values=1)
content_tensor = tf.pad(content_tensor, [[min_y_, ((image_height - 1) - max_y_)], [min_x_, ((image_width - 1) - max_x_)], [0, 0]], constant_values=0)
return ((image_ * mask) + content_tensor) | -1,229,225,343,436,366,000 | Applies mask to bbox region in image then adds content_tensor to it. | efficientdet/aug/autoaugment.py | mask_and_add_image | datawowio/automl | python | def mask_and_add_image(min_y_, min_x_, max_y_, max_x_, mask, content_tensor, image_):
mask = tf.pad(mask, [[min_y_, ((image_height - 1) - max_y_)], [min_x_, ((image_width - 1) - max_x_)], [0, 0]], constant_values=1)
content_tensor = tf.pad(content_tensor, [[min_y_, ((image_height - 1) - max_y_)], [min_x_, ((image_width - 1) - max_x_)], [0, 0]], constant_values=0)
return ((image_ * mask) + content_tensor) |
def scale_channel(image):
'Scale the 2D image using the autocontrast rule.'
lo = tf.to_float(tf.reduce_min(image))
hi = tf.to_float(tf.reduce_max(image))
def scale_values(im):
scale = (255.0 / (hi - lo))
offset = ((- lo) * scale)
im = ((tf.to_float(im) * scale) + offset)
im = tf.clip_by_value(im, 0.0, 255.0)
return tf.cast(im, tf.uint8)
result = tf.cond((hi > lo), (lambda : scale_values(image)), (lambda : image))
return result | 1,234,125,559,131,667,000 | Scale the 2D image using the autocontrast rule. | efficientdet/aug/autoaugment.py | scale_channel | datawowio/automl | python | def scale_channel(image):
lo = tf.to_float(tf.reduce_min(image))
hi = tf.to_float(tf.reduce_max(image))
def scale_values(im):
scale = (255.0 / (hi - lo))
offset = ((- lo) * scale)
im = ((tf.to_float(im) * scale) + offset)
im = tf.clip_by_value(im, 0.0, 255.0)
return tf.cast(im, tf.uint8)
result = tf.cond((hi > lo), (lambda : scale_values(image)), (lambda : image))
return result |
def scale_channel(im, c):
'Scale the data in the channel to implement equalize.'
im = tf.cast(im[:, :, c], tf.int32)
histo = tf.histogram_fixed_width(im, [0, 255], nbins=256)
nonzero = tf.where(tf.not_equal(histo, 0))
nonzero_histo = tf.reshape(tf.gather(histo, nonzero), [(- 1)])
step = ((tf.reduce_sum(nonzero_histo) - nonzero_histo[(- 1)]) // 255)
def build_lut(histo, step):
lut = ((tf.cumsum(histo) + (step // 2)) // step)
lut = tf.concat([[0], lut[:(- 1)]], 0)
return tf.clip_by_value(lut, 0, 255)
result = tf.cond(tf.equal(step, 0), (lambda : im), (lambda : tf.gather(build_lut(histo, step), im)))
return tf.cast(result, tf.uint8) | 6,353,019,026,156,998,000 | Scale the data in the channel to implement equalize. | efficientdet/aug/autoaugment.py | scale_channel | datawowio/automl | python | def scale_channel(im, c):
im = tf.cast(im[:, :, c], tf.int32)
histo = tf.histogram_fixed_width(im, [0, 255], nbins=256)
nonzero = tf.where(tf.not_equal(histo, 0))
nonzero_histo = tf.reshape(tf.gather(histo, nonzero), [(- 1)])
step = ((tf.reduce_sum(nonzero_histo) - nonzero_histo[(- 1)]) // 255)
def build_lut(histo, step):
lut = ((tf.cumsum(histo) + (step // 2)) // step)
lut = tf.concat([[0], lut[:(- 1)]], 0)
return tf.clip_by_value(lut, 0, 255)
result = tf.cond(tf.equal(step, 0), (lambda : im), (lambda : tf.gather(build_lut(histo, step), im)))
return tf.cast(result, tf.uint8) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.