How to merge (join) two wx.bitmap using wxpython? - python

I have one wx.emptybitmap (1) and one wx.bitmap (2). I want to merge(join) them..
I want to create a single wx.bitmap that consists on the wx.emptybitmap (1) on the top and wx.bitmap (2) on the bottom.
How can I do that?
Thanks in advance! :D

After a lot of web searching here it is :)
The code is something like that!
empty = wx.EmptyBitmap(parent.imageWidth,12+parent.imageHeight)
dc = wx.MemoryDC()
dc.SelectObject(empty)
dc.SetTextForeground(parent.colorFont)
dc.SetPen(wx.Pen('WHITE', 1))
dc.DrawLine(0, 3, parent.imageWidth, 3)
dc.DrawLine(0, 6, parent.imageWidth, 6)
dc.DrawLine(0, 9, parent.imageWidth, 9)
dc.DrawBitmap(imageSmall[len(imageSmall)-1], 0, 12, True)
dc.SelectObject(wx.NullBitmap)
wx.StaticBitmap.__init__(self, parent, id, bitmap=empty, pos=(position[0], position[1]), size=(parent.imageWidth, parent.imageHeight))

You could always use PIL, it has a function to do this. Save the image in memory and convert it into an wx.Bitmap.

Related

How does the 'with' statement work in kivy?

I have been playing with kivy, and I saw this:
with self.canvas:
Color(1, 1, 0) # <--- no assignment
d = 30.
Ellipse(pos=(touch.x - d / 2, touch.y - d / 2), size=(d, d)) # <--- no assignment
I don't quite understand how it works. I was expecting to see something like:
with self.canvas as c:
c.color = Color(1, 1, 0)
c.shape = Ellipse()
What am I missing?
with some_canvas sets an internal Kivy variable to that canvas. When canvas instructions are created they check if that variable is set to a canvas, and if so they automatically add themselves to it.
If you want to trace through how this works you can find the context entry function here, and the code that automatically adds instructions to a canvas when instantiated here.
I don't quite understand how it works. I was expecting to see something like:
with self.canvas as c:
c.color = Color(1, 1, 0)
c.shape = Ellipse()
In this case the with context wouldn't really be doing anything. If you want to explicitly manipulate the canvas you can do it directly without a context manager, e.g. self.canvas.add(Color(1, 1, 0)).
That said, the way you've written this may indicate a misunderstanding: a canvas doesn't have a specific colour as you've indicated with c.color, rather it's a list of instructions to apply in order. There could be many Color instructions, with different numbers of other instructions (e.g. representing different shapes) in between.

How do I get indices around certain values in an array

So I came accros this tiny but tricky problem.
I have an array of indices of error_images, something like this:
error_frames = [15,27,34,204,205]
Now I am using a for loop to iterate over these frames and add 10 frames in prior and after the erroneous frames in order to get a sequence, so that in the end, the array is more populated. I also removed duplicates (excuse MATLAB writing):
error_sequence = [5:44,194:215]
Now the tricky part:
In Order to show the sequence, I load every image and show it for a certain time using OpenCV cv2.imshow. When actually encountering an error, I want to increase the pause between shown images ('slow motion') and have a special overlay. This looks like this, where frames is a collection of my pictures of the scene:
for x in error_sequence:
if x in error_frames:
cv2.imshow('Sequence', frames[x])
cv2.putText(frames[x], "Error!", (50, 50),
cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), 3)
cv2.waitKey(100)
else:
cv2.imshow('Sequence', frames[x])
cv2.waitKey(50)
The problem is, that this "one-frame" overlay is way too fast and I want to slow down more frames, lets say 3 before and after the encountered error.
Is there some kind of function, that lets me do that? Something like:
if x+-3 in error_frames:
...
Thank you for your help and sorry, if this is an easy question, I don't know how else to describe it. And yes, I could come up with an extra array that I set to 0 if it is further away from an error frame than 3 and use a seperate if case, but I don't find that very attractive and was wondering if there is a built in function or a nice "one-liner" ;)
Perhaps something like this:
error_frames_set = set(error_frames)
delta = 3
for x in error_sequence:
slow_frames = set(x + offset for offset in range(-delta, delta+1))
if slow_frames.intersection(error_frames_set):
cv2.imshow('Sequence', frames[x])
cv2.putText(frames[x], "Error!", (50, 50),
cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), 3)
cv2.waitKey(100)
else:
cv2.imshow('Sequence', frames[x])
cv2.waitKey(50)
Like so maybe:
if any(y in error_frames for y in xrange(x-3, x+4)):
...
You can consider creating a set out of your error_frames to improve the time complexity of the contains-check:
error_frame_set = set(error_frames)
And then use this set in all the checks.

using enumerate to iterate over a dictionary of lists to extract information

I got some help earlier today about how to obtain positional information from a dictionary using enumerate(). I will provide the code shortly. However, now that I've found this cool tool, I want to implement it in a different manner to obtain some more information from my dictionary.
I have a dictionary:
length = {'A': [(0,21), (30,41), (70,80), (95,200)] 'B': [(0,42), (70,80)]..etc}
and a file:
A 73
B 15
etc
What I want to do now is to find the difference from the max of the first element in my list from the min from the second element. For example, the difference of 21 and 30. Then I want to add all these differences up until I hit the pair (range) of numbers that the number from my file matches to (if that makes sense).
Here is the code that I've been working on:
import csv
with open('Exome_agg_cons_snps_pct_RefSeq_HGMD_reinitialized.txt') as f:
reader = csv.DictReader(f,delimiter="\t")
for row in reader:
snppos = row['snp_rein']
name = row['isoform']
snpos = int(snppos)
if name in exons:
y = exons[name]
for sd, i in enumerate(exons[name]):
while not snpos<=max(i):
intron = min(i+1) - max(i) #this doesn't work unfortunately. It says I can't add 1 to i
totalintron = 0 + intron
if snpos<=max(i):
exonmin = min(i)
exonnumber = sd+1
print exonnumber,name,totalintron
break
I think it's the sd (indexer) that is confusing me. I don't know how to use it in the this context. The commented out portions are other avenues I've tried but failed to be successful. Any help? I know this is a confusing question and my code might be a little mixed up, but that's because I can't even get an output to correct my other mistakes yet.
I want my output to look like this based on the file provided:
exon name introntotal
3 A 38
1 B 0
To try to provide some help for this question: a critical part of the problem is that I don't think enumerate does what you think it does. Enumerate just numbers the things you are iterating over. So when you go through your for loop, sd will first be 0, then it will be 1... And that's all. In your case, you want to look at adjacent list entries (it seems?), so the more idiomatic ways of looping in python aren't nearly as clean. So you could do something like:
...
y = exons[name]
for index in range(len(y) - 1): # the - 1 is to prevent going out of bounds
first_max = max(y[index])
second_min = min(y[index+1])
... # do more stuff, I didn't completely follow what you're trying to do
I will add for the hardcore pythonistas, you can of course do some clever stuff to write this more idiomatically and avoid the C style loop that I wrote, but I think that getting into zip and so on might be a bit confusing for somebody new to python.
The issue is that you're using the output of enumerate() incorrectly.
enumerate() returns the index (position) first then the item
Ex:
x = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
for i, item in enumerate(x):
print(i, item)
# prints
#(0, 10)
#(1, 11)
#(2, 12)
#(3, 13)
#(4, 14)
#(5, 15)
#(6, 16)
#(7, 17)
#(8, 18)
#(9, 19)
So in your case, you should switch i and sd:
for i, sd in enumerate(exons[name]):
# do something
Like other commenters suggested, reading the python documentation is usually a good place to start resolving issues, especially if you're not sure how a function does what it does :)

PYGTK uses more screen space than expected

I am using PYGTK to program a very simple download manager, using both wGet and Python. Everything does well but it eats up a lot of screen space...
My code:
#!/usr/bin/python
import gtk
import os
def submitdownload(self):
os.system("wget "+site.get_text() + " -P "+ directory.get_text())
main=gtk.Window()
main.set_title("Simple Downloader with wGet")
structure=gtk.Table(2, 6, True)
label=gtk.Label("Simple downloader with wGet")
sitedes=gtk.Label("Your download link:")
site=gtk.Entry()
submit=gtk.Button("Submit download")
submit.connect("clicked", submitdownload)
directorydes=gtk.Label("Save to: ")
directory=gtk.Entry()
description=gtk.Label("Please don't close the black box (terminal window) or the application will close automatically. It is needed for the download.")
main.add(structure)
structure.attach(label, 0, 2, 0, 1)
structure.attach(sitedes, 0, 1, 1, 2)
structure.attach(site, 1, 2, 1, 2)
structure.attach(submit, 0, 2, 4, 5)
structure.attach(directorydes, 0, 1, 2, 3)
structure.attach(directory, 1, 2, 2, 3)
structure.attach(description, 0, 2, 5, 6)
main.connect("destroy", lambda w: gtk.main_quit())
main.show_all()
gtk.main()
It throws a lot of unused space at the right. How to fix that? It's very hard to close the application through the 'X' button.
You appear to be creating a table with 2 rows and 6 columns as opposed to the 6 rows and 2 columns I assume you're after - look at the reference documentation and you'll see rows come first in the constructor.
Because you've set homogenous to True, the table is setting all columns to the same width and height (that's what homogenous does), and because you've asked for 6 columns, it's adding a lot of blank ones of the same width which makes your window tremendously wide.
Change the line to:
structure = gtk.Table(6, 2, True)
... and it seems more reasonable. Was that what you were after?
Personally I would suggest creating a HBox to represent the column. When you need full width widgets, you can just place them directly into this container. If you need a row with multiple widgets, you can create a VBox to represent the row, add the widgets to that and then add the VBox itself to the HBox. This approach may seem slightly fiddlier at first, but it allows GTK to handle more of the layout itself which generally makes your application handle resizing better (as long as you correctly hint whether each widget should be expandable or not). Also, you don't need to go back and change the number of rows and columns if you add more widgets later - VBox and HBox are more flexible in that regard. So overall, I've always found these a lot easier unless what I'm after really is a fixed grid of widgets (e.g. if I'm implementing Minesweeper).

ArcGIS 10 python - Conditional statement checking to see if a raster value is in a set

I am attempting to create a raster based on input from another raster.
If a raster value is equal to a number included in a set() than I want it to be 1, else 0
I've attempted the following:
ConfusedRaster = arcpy.Con(inraster in repeatSet, 1, 0)
and
ConfusedRaster = arcpy.Con(inraster, 1, 0, "inraster in repeatSet")
Neither of these work. I believe they don't work because the where clause only accepts Map Algebra expressions: ArcGIS Help
There are two other ways I can think of doing this. One being converting it to a NumPyArray and working with that. The other is looping through the set and creating a raster object for each value in the set. After the loop has finished merge them.
Does anyone have any suggestions or comments on how to go about this?
Thank you
I was searching for an answer to the similar issue and developed a way using the SQL clause in 'ExtractByAttributes'.
repeatList = list(repeatSet)
ras1 = arcpy.sa.ExtractByAttributes(inraster, 'VALUE IN (' + str(repeatList).strip('[]') + ')')
ConfusedRaster = arcpy.sa.Con(arcpy.sa.IsNull(ras1) == 0, 1, 0)

Categories