예제 #1
0
파일: texture5.py 프로젝트: kzfm1024/misc
def scene():
    color = [ 1.0, 1.0, 1.0, 1.0 ]
    #color = [ 1.0, 0.0, 0.0, 1.0 ]
    glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, color)

    #glEnable(GL_ALPHA_TEST)
    glEnable(GL_TEXTURE_2D)

    glEnable(GL_TEXTURE_GEN_S)
    glEnable(GL_TEXTURE_GEN_T)
    glEnable(GL_TEXTURE_GEN_R)
    glEnable(GL_TEXTURE_GEN_Q)

    glPushMatrix()
    glTranslated(-1.2, 0.0, 0.0)
    box(1.0, 1.0, 1.0)
    glPopMatrix()
    glPushMatrix()
    glTranslated(1.2, 0.0, 0.0)
    box(1.0, 1.0, 1.0)
    glPopMatrix()

    glDisable(GL_TEXTURE_GEN_S)
    glDisable(GL_TEXTURE_GEN_T)
    glDisable(GL_TEXTURE_GEN_R)
    glDisable(GL_TEXTURE_GEN_Q)

    glDisable(GL_TEXTURE_2D)
예제 #2
0
파일: texture2.py 프로젝트: kzfm1024/misc
def scene():
    color = [ 1.0, 1.0, 1.0, 1.0 ]
    #color = [ 1.0, 0.0, 0.0, 1.0 ]
    glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, color)

    glEnable(GL_ALPHA_TEST)
    glEnable(GL_TEXTURE_2D)

    box(1.0, 1.0, 1.0)

    glDisable(GL_TEXTURE_2D)
    glDisable(GL_ALPHA_TEST)
예제 #3
0
파일: gui.py 프로젝트: casibbald/kamaelia
def main():
    pygame.init()
    screen = display.set_mode((640, 480))
    display.set_caption('shard gui')
    
    screen.fill(colours['white'])
    pygame.display.update()
    
    t = toolbar(things = [box('label.png'), box('label.png')])
    c = cancel('label.png')
    cl = clear('label.png')
    f = forward('label.png')
    b = back('label.png')
    t.add([c, cl, b, f])
    g = grid(screen, 0, t.height, screen.get_width(), screen.get_height()-t.height)
    
    con = container(t, g, screen)
    
    done = False
    while not done:
        rs = con.draw(screen)
        display.update(rs)
        
        events = pygame.event.get()
        for e in events:
            if(e.type == QUIT):
                done = True
                break
            elif(e.type == KEYDOWN):
                if(e.key == K_ESCAPE):
                    done = True
                    break
            else:
                con.handleEvent(e)

    return
예제 #4
0
def report_error(message, filename, line=None, src='', traceback=None, prefix=u'ERROR'):
    """
    Helper for reporting error to logging module.

    Inputs:
        message[str]: The message to report, ERROR is automatically appended
        page[pages.Page]: The page that created the error
        info[Information]: The lexer information object
        traceback: The traceback (should be a string from traceback.format_exc())
    """
    title = '{}: {}'.format(prefix, message)
    if src:
        src = mooseutils.colorText(box(src, line=line, width=100), 'LIGHT_CYAN')

    if line is not None:
        filename = mooseutils.colorText('{}:{}\n'.format(filename, line), 'RESET')
    else:
        filename = mooseutils.colorText('{}\n'.format(filename), 'RESET')

    trace = u'\n' + mooseutils.colorText(traceback, 'GREY') if traceback else ''
    return u'\n{}\n{}{}{}\n'.format(title, filename, src, trace)
def calc_box_ema_spectra_mse(Neff, Nbox, Nwindow):
    "Mean-Squared Error\
     1) generates h_ema and h_box given the input parameters;\
     2) takes the amplitude of the FFT for each response\
     3) computes the cumulative sum of each gain spectrum\
     4) computes and retuns the MSE of the two cumulative gain spectra"

    h_box = box(Nbox, Nwindow)
    h_ema = ema(Neff, Nwindow)

    h_box_fft = np.fft.fft(h_box)
    h_ema_fft = np.fft.fft(h_ema)

    h_box_fft_abs = np.absolute(h_box_fft) 
    h_ema_fft_abs = np.absolute(h_ema_fft) 

    h_box_fft_abs_sum = np.cumsum(h_box_fft_abs)
    h_ema_fft_abs_sum = np.cumsum(h_ema_fft_abs)

    mse = np.sum(np.square(h_box_fft_abs_sum - h_ema_fft_abs_sum)) / Nwindow
   
    return mse 
예제 #6
0
파일: main.py 프로젝트: arnabGudu/pi_ws
S = cv.getTrackbarPos('S', 'thresh')
V = cv.getTrackbarPos('V', 'thresh')

hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)
thresh = cv.inRange(hsv, (h, s, v), (H, S, V))
#cv.imshow('thresh', thresh)
show(thresh)
whites = cv.inRange(hsv, (0, 0, v), (H, S, V))
show(whites ^ thresh)

order = sort.shorted(img, thresh)

pt1 = order[0][2]
print('point 1:', pt1)

mid_box = box.box(img)

for i in range(1, len(order)):
    pt2 = order[i][2]
    mid = ((pt2[0] + pt1[0]) / 2, (pt2[1] + pt1[1]) / 2)
    angle = math.atan2(pt2[1] - pt1[1], pt2[0] - pt1[0])
    dist = []
    for pts in mid_box:
        dist.append(math.hypot(mid[0] - pts[0], mid[1] - pts[1]))

    min_dist = min(dist)
    j = dist.index(min_dist)

    #april_ang, april_center = april.april(img)

    #theta = angle - april_ang
예제 #7
0
파일: default.py 프로젝트: ddurdle/KODI-Box
    else:
        # show index of accounts
        if instanceName == '' and numberOfAccounts == 1:

                count = 1
                max_count = int(addon.getSetting(PLUGIN_NAME+'_numaccounts'))
                loop = True
                while loop:
                    instanceName = PLUGIN_NAME+str(count)
                    try:
                        username = addon.getSetting(instanceName+'_username')
                        if username != '':

                            #let's log in
                            oc = box.box(PLUGIN_URL,addon,instanceName, user_agent)
                            loop = False
                    except:
                        break

                    if count == max_count:
                        break
                    count = count + 1

        # no accounts defined
        elif numberOfAccounts == 0:

            #legacy account conversion
            try:
                username = addon.getSetting('username')
예제 #8
0
def ImageDetect(pimg, box_list):
    img = pimg[:]
    (thresh, img_bin) = cv2.threshold(
        img, 128, 255,
        cv2.THRESH_BINARY | cv2.THRESH_OTSU)  # Thresholding the image
    img_bin = 255 - img_bin  # Invert the Image_bin
    #cv2.imwrite("Image_bin.jpg",img_bin)

    # Defining a kernel length
    kernel_length = np.array(img).shape[1] // 40

    # A verticle kernel of (1 X kernel_length), which will detect all the verticle lines from the image.
    verticle_kernel = cv2.getStructuringElement(cv2.MORPH_RECT,
                                                (1, kernel_length))

    # A horizontal kernel of (kernel_length X 1), which will help to detect all the horizontal line from the image.
    hori_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (kernel_length, 1))

    # A kernel of (3 X 3) ones.
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))

    # Morphological operation to detect verticle lines from an image
    img_temp1 = cv2.erode(img_bin, verticle_kernel, iterations=3)
    verticle_lines_img = cv2.dilate(img_temp1, verticle_kernel, iterations=3)
    #cv2.imwrite("verticle_lines.jpg",verticle_lines_img)

    # Morphological operation to detect horizontal lines from an image
    img_temp2 = cv2.erode(img_bin, hori_kernel, iterations=3)
    horizontal_lines_img = cv2.dilate(img_temp2, hori_kernel, iterations=3)
    #cv2.imwrite("horizontal_lines.jpg",horizontal_lines_img)

    # Weighting parameters, this will decide the quantity of an image to be added to make a new image.
    alpha = 0.5
    beta = 1.0 - alpha

    # This function helps to add two image with specific weight parameter to get a third image as summation of two image.
    img_final_bin = cv2.addWeighted(verticle_lines_img, alpha,
                                    horizontal_lines_img, beta, 0.0)
    img_final_bin = cv2.erode(~img_final_bin, kernel, iterations=2)
    (thresh,
     img_final_bin) = cv2.threshold(img_final_bin, 128, 255,
                                    cv2.THRESH_BINARY | cv2.THRESH_OTSU)

    # For Debugging
    # Enable this line to see verticle and horizontal lines in the image which is used to find boxes
    #cv2.imwrite("img_final_bin.jpg",img_final_bin)

    contours, hierarchy = cv2.findContours(img_final_bin, cv2.RETR_TREE,
                                           cv2.CHAIN_APPROX_SIMPLE)
    # Sort all the contours by top to bottom.
    #(contours, boundingBoxes) = sort_contours(contours, method="top-to-bottom")

    _, _, page_width, _ = cv2.boundingRect(contours[0])

    for c in range(1, len(contours), 2):
        # Returns the location and width,height for every contour
        x, y, w, h = cv2.boundingRect(contours[c])
        if (w > 20 and h > 20):
            box_Object = box.box(x, y, x + w, y + h, "Image", None, -1)
            box_list.append(box_Object)

    return (box_list, page_width)
예제 #9
0
    else:
        # show index of accounts
        if instanceName == '' and numberOfAccounts == 1:

            count = 1
            max_count = int(addon.getSetting(PLUGIN_NAME + '_numaccounts'))
            loop = True
            while loop:
                instanceName = PLUGIN_NAME + str(count)
                try:
                    username = addon.getSetting(instanceName + '_username')
                    if username != '':

                        #let's log in
                        oc = box.box(PLUGIN_URL, addon, instanceName,
                                     user_agent)
                        loop = False
                except:
                    break

                if count == max_count:
                    break
                count = count + 1

        # no accounts defined
        elif numberOfAccounts == 0:

            #legacy account conversion
            try:
                username = addon.getSetting('username')
예제 #10
0
import socket
import re
import logging
from box import Box as box
from colorama import Back, Fore, init, Style
from aiohttp import client_exceptions as clientExcps

init(autoreset=True)

colorSchemes = {
    'SUCCESS': f"{Back.GREEN}{Fore.BLACK}{Style.NORMAL}",
    'FAILURE': f"{Back.RED}{Fore.WHITE}{Style.BRIGHT}",
    'WARNING': f"{Back.YELLOW}{Fore.BLACK}{Style.BRIGHT}",
    'RESET': f"{Style.RESET_ALL}"
}
colorSchemes = box(colorSchemes)

logging.basicConfig(format=f'{colorSchemes.FAILURE}[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s', level=logging.ERROR)



bot = discord.Client()
baseUrl = f"https://api.telegram.org/bot{config.TELEGRAM_BOT_TOKEN}"


def replaceMentions(mentions, msg, channel):
    if channel:
        for ch in mentions:
            # msg = msg.replace(str(f"#{ch.id}"), '')
            msg = re.sub(f"<#{ch.id}>", '', msg)
            msg = re.sub(f"<{ch.id}>", '', msg)
예제 #11
0
 def test_negative_input(self):
     self.assertEqual(box(self.data[4][0], self.data[4][1]), None)
예제 #12
0
            try:

                z_cord = sum(z_cutoff) / len(z_cutoff)

            except ZeroDivisionError:

                continue

            com.append([x_cord, y_cord, z_cord])
            out1 = open(os.path.join(curdir, new + 'out' + '_com ' + '.txt'),
                        'w')
            out1.write(str(com))
            out1.close()

            one_comp = box.box([x_cord, y_cord, z_cord])
            out2 = open(os.path.join(curdir, new + 'out' + '_box ' + '.txt'),
                        'w')
            out2.write(str(one_comp))
            out2.close()

            x_max = max(one_comp[0])
            x_min = min(one_comp[0])
            y_max = max(one_comp[1])
            y_min = min(one_comp[1])
            z_max = max(one_comp[2])
            z_min = min(one_comp[2])

            ranges = [x_max, x_min, y_max, y_min, z_max, z_min]
            out3 = open(os.path.join(curdir, new + 'out' + '_range ' + '.txt'),
                        'w')
예제 #13
0
            merge = open('%s/plr.txt' % srce).readlines()
            final = []

            for info in merge[:]:

                final_lists = list(info.split()[1:])
                final.append(final_lists)

            for resi in final[:]:

                resi = '\t'.join([str(x) for x in resi])
                plr_list.write("%s\n" % resi)

            plr_list.close()

            ax.scatter([x for x in xcors], [y for y in ycors],
                       [z for z in zcors],
                       alpha=0.2,
                       color="r")

            comname = range_paths[i].split('/')[-1].split('_')[0] + "_com .txt"
            compath = srce + '/' + comname
            comfiles = open(compath).read().strip('[').strip(']').split(',')

            points = box.box(
                [float(comfiles[0]),
                 float(comfiles[1]),
                 float(comfiles[2])])
            plt.savefig('filter.png')
        plt.close("all")
예제 #14
0
from box import box

obj = box(12, 33, "RED")
print("Box1")
print("The length of the box is :", obj.length)
print("The width of the box is :", obj.width)
print("The colour of the box is :", obj.colour)
print("The Area of the box is:", obj.area)
print("The Parameter of the box is:", obj.parameter)

obj2 = box(10, 2, "RED")

print("\n Box2")
print("The length of the box is :", obj2.length)
print("The width of the box is :", obj2.width)
print("The colour of the box is :", obj2.colour)
print("The Area of the box is:", obj2.area)
print("The Parameter of the box is:", obj2.parameter)
예제 #15
0
 def generate_boxes(self, row, column):
     boxes = []
     for row in range(row):
         for col in range(column):
             boxes.append(box(row, col))
     return boxes
예제 #16
0

if __name__ == "__main__":

    N = 10000
    L = 10 | units.parsec
    rho = 1.14 * 1 | units.amu / units.cm**3
    u = (5.e11 | units.erg / units.g).in_(units.cm**2 / units.s**2)  # =5000K

    tend = 1. | units.Myr
    dt = 10000 | units.yr

    print(u**0.5).in_(units.kms)
    print((L / u**0.5) / dt)

    particles = box(N, L, rho, u)

    UnitLength = L
    UnitMass = particles.mass.sum()
    UnitVelocity = units.kms

    convert = generic_unit_converter.ConvertBetweenGenericAndSiUnits(
        UnitLength, UnitMass, UnitVelocity)
    sph = Gadget2(convert, mode='periodic_nogravity')  #,redirection='none')

    sph.parameters.periodic_box_size = L

    sph.gas_particles.add_particles(particles)

    i = 0
    t = 0. | units.Myr
예제 #17
0
 def test_raises_exception_with_bad_arguments(self):
     with self.assertRaises(Exception):
         box(length=0, width=0, height=0)
예제 #18
0
 def test_creates_box_with_valid_arguments(self):
     result = box(1, 1, 1)
     self.assertIsNotNone(result['model'])
     self.assertIsNotNone(result['computed'])
     self.assertEqual(result['computed']['volume'], 1)
axarr[0, 0].set_ylim(0, 1.1)
axarr[0, 0].set_title("Ideal delay")
axarr[0, 0].plot(impulse_response_fde)
axarr[0, 0].plot(impulse_response_direct, 'o', markerfacecolor='none')

# b) Box

Nbox = 32
lag = 1

impulse = np.zeros(Nwindow)
impulse[lag] = 1

candidate = apply_box_filter(impulse, Nbox)
impulse_response_fde = candidate[lag:]
impulse_response_direct = box(Nbox, Nwindow)

axarr[0, 1].set_title("Box")
axarr[0, 1].plot(impulse_response_fde)
axarr[0, 1].plot(impulse_response_direct, 'o', markerfacecolor='none')

# c) Ema

Neff = 32
lag = 1

impulse = np.zeros(Nwindow)
impulse[lag] = 1

candidate = apply_ema_filter(impulse, Neff)
impulse_response_fde = candidate[lag:]
예제 #20
0
		if item.startswith('ATOM'):
			item = item.replace('',"")
			item = item.split()
			if item[4] == chain_name:
				#print item
				x.append(float(item[6]))
				y.append(float(item[7]))
				z.append(float(item[8]))
	
	for item in z[:]:
		if -15.0<= item and item <=15.0:
			z_select.append(item)
				
	x_cord = sum(x)/len(x)
	y_cord = sum(y)/len(y)
	z_cord = sum(z_select)/len(z_select)
	one_comp = box.box((x_cord,y_cord,z_cord))
	out1 = open(names + '_box ' + '.txt','w')
	out1.write(str(one_comp))
	out1.close()
	
	##########################3d-plot###################################
	
	centre = ax.scatter([x_cord],[y_cord],[z_cord],color="g",s=100)
	points = box.box((x_cord,y_cord,z_cord))
	scatterfile = ax.scatter(points[0], points[1], points[2],color = "r")
	plt.show()

invokepores.invoke()

예제 #21
0
import numpy as np
import matplotlib.pyplot as plt

from ema import ema
from box import box
from comb import comb

Nwindow = 1024

# (a) Ema and box
Neff = 32
h_ema = ema(Neff, Nwindow)

Nbox = Neff / (1-np.exp(-1))
h_box = box(Nbox, Nwindow)

# (b) Comb with period = 256
Nperiod = 256
h_comb = comb(Nperiod, Nwindow)

# (c-f) Convolution
candidate1 = np.convolve(h_comb, h_ema)
candidate2 = np.convolve(h_comb, h_box)

h_ema_replicated = candidate1[:Nwindow]
h_box_replicated = candidate2[:Nwindow]

H_ema = np.absolute(np.fft.fft(h_ema))
H_box = np.absolute(np.fft.fft(h_box))
H_ema_replicated = np.absolute(np.fft.fft(h_ema_replicated)) / Nperiod
# Image
aspect_ratio = 16 / 9
width = 400
height = int(width / aspect_ratio)

samples_per_pixel = None

# World
background = glm.vec3(1, 1, 1)  # background color

diffuse_material = lambertian(glm.vec3(.5, .2, .1))

world = cornell_box()
world.add(sphere(glm.vec3(-1.0, -.5, -1.5), .5, diffuse_material))
world.add(box(glm.vec3(.5, -.9, -2.5), glm.vec3(1, -.4, -2), diffuse_material))
metallic_material = metal(.01, glm.vec3(0.5, 0.5, 0.2))
world.add(sphere(glm.vec3(.0, -.5, -1.5), .5, metallic_material))

# Camera
cam = camera()

output_file = sys.argv[1] if len(sys.argv) > 1 else 'problem1' + '.ppm'
samples_per_pixel = int(sys.argv[2].strip()) if len(sys.argv) > 2 else 1
max_depth = int(sys.argv[3].strip()) if len(sys.argv) > 3 else 100

with open(output_file, 'w') as f:
    f.write('P3\n%d %d\n255\n' % (width, height))
    for j in tqdm(range(height - 1, -1, -1), desc='loading:'):
        for i in range(width):
            color = glm.vec3(0, 0, 0)
예제 #23
0
# init sender for pitch and volume
sender = com.ThereminCommunication()
sender.connect()

# get the camera
cap = cv2.VideoCapture(0)
fps = fpsCounter.FpsCounter()

# determine the image resolution
width = int(cap.get(3))
height = int(cap.get(4))
print("This Video Resulation is " + str(width) + " by " + str(height))

# init box with image resolution
boxer = box.box(width, height)

while (True):
    # Capture new frame
    fps.newFrame()
    ret, frame = cap.read()
    frame = cv2.flip(frame, 1)

    # get individual sections for pitch and volume
    volSection, pitchSection = boxer.getVolPitchSection(frame)

    # find colored points in each sections
    pointsVol = cf.findColor(volSection, 'red', False)
    pointsPitch = cf.findColor(pitchSection, 'red', False)

    # transform coordinates back to the full frame
예제 #24
0
global_vars.batch = pyglet.graphics.Batch()
global_vars.background = pyglet.graphics.OrderedGroup(0)
global_vars.foreground = pyglet.graphics.OrderedGroup(1)

Objects = []

Player = player(400, 250, 'playerr1.png', Objects)

Platform1 = platform(80, 280, 'platform.png', 30, 260, Objects)
Platform2 = platform(110, 260, 'platform.png', 60, 260, Objects)
Platform3 = platform(140, 240, 'platform.png', 90, 260, Objects)
Platform4 = platform(170, 220, 'platform.png', 120, 260, Objects)
Platform5 = platform(200, 200, 'platform.png', 150, 360, Objects)

Box = box(450, 400, 'box.png', Objects)
Box = box(470, 400, 'box.png', Objects)
Box = box(490, 400, 'box.png', Objects)
Box = box(510, 400, 'box.png', Objects)
Box = box(530, 400, 'box.png', Objects)
Box = box(550, 400, 'box.png', Objects)
Box = box(570, 400, 'box.png', Objects)
Box = box(590, 400, 'box.png', Objects)
Box = box(450, 440, 'box.png', Objects)
Box = box(470, 440, 'box.png', Objects)
Box = box(490, 440, 'box.png', Objects)
Box = box(510, 440, 'box.png', Objects)
Box = box(530, 440, 'box.png', Objects)
Box = box(550, 440, 'box.png', Objects)
Box = box(570, 440, 'box.png', Objects)
Box = box(590, 440, 'box.png', Objects)
axarr[0, 0].set_ylim(0, 1.1)
axarr[0, 0].set_title("Ideal delay")
axarr[0, 0].plot(impulse_response_fde)
axarr[0, 0].plot(impulse_response_direct, 'o', markerfacecolor='none')

# b) Box

Nbox = 32
lag = 1

impulse = np.zeros(Nwindow)
impulse[lag] = 1

candidate = apply_box_filter(impulse, Nbox)
impulse_response_fde = candidate[lag:]
impulse_response_direct = box(Nbox, Nwindow)

axarr[0, 1].set_title("Box")
axarr[0, 1].plot(impulse_response_fde)
axarr[0, 1].plot(impulse_response_direct, 'o',markerfacecolor='none')

# c) Ema

Neff = 32
lag = 1

impulse = np.zeros(Nwindow)
impulse[lag] = 1

candidate = apply_ema_filter(impulse, Neff)
impulse_response_fde = candidate[lag:]
예제 #26
0
 def test_zero_box(self):
     self.assertEqual(box(self.data[2][0], self.data[2][1]), None)
예제 #27
0
 def test_one_by_one(self):
     self.assertEqual(box(self.data[3][0], self.data[3][1]), None)
예제 #28
0
 def __init__(self, message, *args, **kwargs):
     err = kwargs.pop('error', None)
     msg = message.format(*args)
     if err is not None:
         msg += u'\n\n{}'.format(box(err))
     Exception.__init__(self, msg.encode('utf-8'))