Change Black pixels to white and vice versa - graphics

Hey there,
I can't figure out how to make Jython realize that the pixel is either (0,0,0) or (255,255,255). Basically I'm just trying to convert all white pixels to black and vice versa.
Here's what i have sofar :S
def changeBlackWhite(picture):
for x in range(getWidth(picture)):
for y in range(getHeight(picture)):
px = getPixel(picture, x, y)
pxRed = getRed(px)
pxBlue = getBlue(px)
pxGreen = getGreen(px)
if pxRed == '255':
if pxBlue == '255':
if pxGreen == '255':
setRed(px, 0)
setBlue(px, 0)
setGreen(px, 0)
Help?! :)

I don't know what library you use, but I think that getRed() will return integer, and not string. Instead:
if pxRed == '255':
try comparing to integer:
if pxRed == 255:

Related

Any way to refactor this in a neater way? Specifically lines 7-11 in relation to line 39? Using Pygame

I am teaching this to 5th graders so it needs to be as simple as possible. However, as you see inline 39 I am using stored variables for the function parameters. However is there an easier way? Let's say I wanted to put in a 2nd character I would have to put that long list of variables again?
Should I create a character class? If so, how would I plug that into a parameter?
import pygame
pygame.init()
win = pygame.display.set_mode((1000, 1000))
#Character Details
x = 100
y = 5
width = 10
height = 10
vel = 20
run = True
while run:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
#Movement Details
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
x -= vel #
if keys[pygame.K_RIGHT]:
x += vel
if keys[pygame.K_UP]:
y -= vel
if keys[pygame.K_DOWN]:
y += vel
#Without this character movement is additive.
win.fill((0, 0, 0))
pygame.draw.rect(win, (245, 100, 50), (x, y, width, height))
pygame.display.update()
```
You could make the variables a Rect object.
player1 = pygame.Rect(100,5,10,10) #x,y,w,h
player2 = pygame.Rect(200,20,10,10)
...
pygame.draw.rect(win,(245,100,50),player1)
pygame.draw.rect(win,(245,100,50),player2)
you could also use a list and it would work just as fine, but with the Rect, it calculates extra attributes for you like
player1.center #get center of the player, both x and y
player.right #get right side of player, same as x position + width
you can also move using these
player1.center = (200,200) #moves the center to (200,200)
But you would need to have a velocity variable for each player, which you could have a list
#The Big Kahuna has already suggested that you can replace one of the parameters to the pygame.draw.rect() with a rect representing the player. That is specifically answering your question and you should do that.
Since you are teaching this to others I wanted to suggest some other things as well.
The first is a tweak to what #The Big Kahuna said. He correctly suggested that you should use the the pygame rect class, which you should. Instead of passing the four parameters like that, Rect allows you you create rect's by calling it with the position and size parameters grouped together. I.e you can group the two position parameters and the two size parameters. Like this:
size = (10, 10) # width, height
player1 = pygame.Rect((100, 5), size)
player2 = pygame.Rect((200, 20), size)
You could separate the position out as well if desired.
The other thing that you can do (and the real reason that I am actually commenting here) to make it cleaner is to look at the other parameter to pygame.draw.rect(). The (245,100,50) is the color you are drawing (see the docs here). Instead of just using numbers like that, it can be made more clear by assigning that color to a variable somewhere near the top of your program and using the variable in the draw call. Like this:
orangey = (245, 100, 50)
...
pygame.draw.rect(win, orangey, player1)
In this case I called the color orangey, because when I displayed it it looked kind of orangey to me. but obviously you can name it whatever is appropriately descriptive.
You can use multiple colors to distinguish the player rect's like this:
orange = pygame.Color("orange")
purple = pygame.Color("purple")
...
pygame.draw.rect(win, orange, player1)
pygame.draw.rect(win, purple, player2)
You can see a good way to find defined colors like the ones I showed by looking at the answer to the question here.

How to make a double loop inside a dictionary in Python?

I have a data cube with 2 dimensions of coordinates and a third dimension for wavelength. My goal is to write a mask for coordinates outside a circle of given radius to the central coordinates (x0 and y0 in my code). For this, I'm trying to use a dictionary, but I'm having throuble because it seems that I'll have to make a double loop inside the dictionary to iterate over the two dimensions, and as a beginner with dictionaries, I don't know yet how to do that.
I wrote the following code
x0 = 38
y0 = 45
radius = 9
xcoords = np.arange(1,flux.shape[1]+1,1)
ycoords = np.arange(1,flux.shape[2]+1,1)
mask = {'xmask': [xcoords[np.sqrt((xcoords[:]-x0)**2 + (y-y0)**2) < radius] for y in ycoords], 'ymask': [ycoords[np.sqrt((x-x0)**2 + (ycoords[:]-y0)**2) < radius] for x in xcoords]}
And it returned several arrays, one for each value of y (for xmasks), and one for each value of x (for ymasks), although I want just one array for each one. Could anyone say what I made wrong and how to achieve my goal?
Note: I also made it without using a dictionary, as
xmask = []
for x in xcoords:
for y in ycoords:
if np.sqrt((x-x0)**2 + (y-y0)**2) < radius:
xmask.append(x)
break
ymask = []
for y in xcoords:
for x in ycoords:
if np.sqrt((x-x0)**2 + (y-y0)**2) < radius:
ymask.append(y)
break
but I hope it's possible to make it more efficiently.
Thanks for any help!
Edit: I realized that no loop was needed. If I select y = y0 and x = x0, I get the values of x and y that are inside the circle, respectively. So I stayed with
mask = {'xmask': [xcoords[abs(xcoords[:]-x0) < radius]], 'ymask': [ycoords[abs(ycoords[:]-y0) < radius]]}
The OP explains that assigning
mask = {'xmask': [xcoords[abs(xcoords[:] - x0) < radius]],
'ymask': [ycoords[abs(ycoords[:] - y0) < radius]]}
solves the problem.

Creating a checkers board in python

It's currently between semesters and I wanted to do a second "final project" for nothing other than practice. I decided to make a checkers game in python.
I'm using the graphics library to do this in. The way I want it to work is to build the board using squares and I want to label each of them as their own entity. I don't know if this can work*** but I want to create a dictionary to store each rectangle and have a value to show if there is a piece there or not. So far this is what I have to build the board....
def board(win,coordSys):
xRange = 'ABCDEFGH'
X = 0
for x in range(1,9):
for y in range(1,9):
Rec = Rectangle(Point(x,y),Point(x+1,y+1))
if x%2 == 0 and y%2 == 0:
Rec.setFill('red')
coordSys[xRange[X]+str(y)] = 0
elif x%2 != 0 and y%2 != 0 :
Rec.setFill('red')
coordSys[xRange[X]+str(y)] = 0
else:
Rec.setFill('grey')
Rec.draw(win)
X+=1
I'm relatively new at Python so i'm trying to do it with the tools that I'm already aware of for now. My question is, how can I store individual rectangles using a A1-H8 format in a dictionary so that I can have {A1:0 etc..} and I'm able to check the value of A1 to see if anything has been altered in A1's rectangle?
If what you want is a dictionary whose values are the rectangles in question, it sounds like what you are looking for is something like
for x in range(1, 9):
for y in range(1, 9):
rec = Rectangle(Point(x, y), Point(x+1, y+1))
coordSys[xRange[x-1] + str(y)] = rec
rec.draw(win)

Changing radius/degree to x,y coordinate for output of a value at a point

I'm working on my final project for class, which is a program that displays the HSV values for a color and then allows the user to click on the color to display it and then choose a lightness value for it. There is a lot of code that I don't want to post here, so I've made a few pastebin posts and linked them here.
My friend/classmate made a circular color wheel, and I am trying to adapt his color selection method into a rectangular color spectrum so we can have both to display for the professor and write about the pros/cons, etc. of each.
My color displays correctly, but I am having trouble getting the color selection to work, and I have a sneaking suspicion that it has to do with this part:
def color_from_point(x, y, l):
degree = abs(degrees(atan(y / x)))
c = abs(x / cos(radians(degree)))
if x < 0 and y >= 0:
degree = (90 - degree) + 90
elif x < 0 and y < 0:
degree = degree + 180
elif x >= 0 and y <= 0:
degree = (90 - degree) + 270
if c > 255:
color = "White"
else:
color = colors(c / 255, degree, (l / 100))
return color
I am a complete beginner coder, and I'm not sure what to do to change this from using radius and degrees to using just the x,y coordinate to give me the color.
Here is the link to the pastebin post of the circular color picker of a friend/classmate:
http://pastebin.com/gAEg6rA1
Link to my WIP rectangular version:
http://pastebin.com/MJcqvvJw
Thanks in advance for any and all help!!

2 bit per pixel tga's color to qRgb

I need to read tga's with pyqt and so far this seems to be working fine except where a tga has 2 bytes per pixel as opposed to 3 or 4. My code is taken from here http://pastebin.com/b5Vz61dZ.
Specifically this section:
def getPixel( file, bytesPerPixel):
'Given the file object f, and number of bytes per pixel, read in the next pixel and return a qRgba uint'
pixel = []
for i in range(bytesPerPixel):
pixel.append(ord(file.read(1)))
if bytesPerPixel==4:
pixel = [pixel[2], pixel[1], pixel[0], pixel[3]]
color = qRgba(*pixel)
elif bytesPerPixel == 3:
pixel = [pixel[2], pixel[1], pixel[0]]
color = qRgb(*pixel)
elif bytesPerPixel == 2:
# if greyscale
color = QColor.fromHsv( 0, pixel[0] , pixel[1])
color = color.value()
return color
and this part:
elif bytesPerPixel == 2:
# if greyscale
color = QColor.fromHsv( 0, pixel[0] , pixel[1])
color = color.value()
how would I input the pixel[0] and pixel[1] values to create get the values in the correct format and colorspace?
Any thoughts, ideas or help please!!!
pixel = [ pixel[1]*2 , pixel[1]*2 , pixel[1]*2 ]
color = qRgb(*pixel)
works for me. Correct luminance and all. Though I'm not sure doubling the pixel[1] value would work for all instances.
Thank you for all the help istepura :)
http://lists.xcf.berkeley.edu/lists/gimp-developer/2000-August/013021.html
"Pixels are stored in little-endian order, in BGR555 format."
So, you have to take "leftmost" 5 bits of pixel[1] as Blue, rest 3 bits + 2 "leftmost" bits of pixel[0] would be Green, and next 5 bits of pixel[0] would be Red.
In your case, I suppose, the code should be something like:
pixel = [(pixel[1]&0xF8)>>3, ((pixel[1]&0x7)<<2)|((pixel[0]&0xC0)>>6), (pixel[0]&0x3E)>>1)
color = qRgb(*pixel)

Resources