I am in my first programming class so very new. I'm trying to count the black pixels in a picture and I'm stuck. This is what I have so far:
def main():
#create a 10x10 black picture
newPict = makeEmptyPicture(10, 10)
show(newPict)
setAllPixelsToAColor(newPict,black)
#Display the picture
show(newPict)
#Initialize variabl countBlack to 0
countZero = 0
for p in getPixels(newPict):
r = getRed(p)
b = getBlue(p)
g = getGreen(p)
if (r,g,b) == (0,0,0):
countZero = countZero + 100
return countZero
How it was pointed by kedar and deets , your return is INSIDE the for, so, in the first pixel it will return the value of countZero, instead of looping over all the image, just fixing the indention should be fine :
for p in getPixels(newPict):
r = getRed(p)
b = getBlue(p)
g = getGreen(p)
if (r,g,b) == (0,0,0):
countZero = countZero + 1
return countZero
Related
I wanna run this code for a wide range instead of this range. So I wanna make it better to run faster.
Is it impossible to use something else instead of these loops?
z1=3
z2=HEIGHT-1
def myfunction(z1,z2):
for l in range(z1):
vector = np.zeros(WIDTH)
vector[WIDTH//2] = 1
result = []
result.append(vector)
for i in range(z2):
vector = doPercolationStep(vector, PROP, i)
result.append(vector)
result = np.array(result)
ss = result.astype(int)
ss = np.where(ss==0, -1, ss)
ww = (ss+(ss.T))/2
re_size = ww/(np.sqrt(L))
matr5 = re_size
np.savetxt('F:/folder/matr5/'+str(l)+'.csv', matr5)
and doPercolationStep is:
WIDTH = 5
HEIGHT = 5
L=5
PROP = 0.6447
def doPercolationStep(vector, PROP, time):
even = time%2 # even is 1 or 0
vector_copy = np.copy(vector)
WIDTH = len(vector)
for i in range(even, WIDTH, 2):
if vector[i] == 1:
pro1 = random.random()
pro2 = random.random()
if pro1 < PROP:
vector_copy[(i+WIDTH-1)%WIDTH] = 1 # left neighbour of i
if pro2 < PROP:
vector_copy[(i+1)%WIDTH] = 1 # right neighbour of i
vector_copy[i] = 0
return vector_copy
I Create function to log transform an image in python. Below is my code..
#Compute Log Only
def logTransform(c, f):
g = c * m.log(float(1+f))
return g
def ImgLogarithmic (img_input, coldepth):
#logarithmatic transform
inputMax = 255
outputMax = 255
c = outputMax/m.log(inputMax+1)
if coldepth != 24:
img_input = img_input.convert('RGB')
img_output = Image.new('RGB', (img_input.size[1], img_input.size[0]))
pixels = img_output.load()
for i in range(img_output.size[0]):
for j in range(img_output.size[1]):
f = img_input.getpixel((i, j))
r = round(logTransform(c, f[0]))
g = round(logTransform(c, f[1]))
b = round(logTransform(c, f[2]))
#b = value * math.log(1 + b)
pixels[i,j] = (r,g,b)
if coldepth == 1:
img_output = img_output.convert("1")
elif coldepth == 8:
img_output = img_output.convert("L")
else:
img_output = img_output.convert("RGB")
return img_output
I create that function to call log transform. But, my code is not working. I think my algorithm is right. Anyone can help? Thank you
I want to draw a box around an image where there are black pixels.
this is my image:(quiz.JPG):
and i would like the image to be something like this:
but with the code below I get this(quiz2.JPG):
here is what i have tried:
from PIL import Image,ImageDraw
image = Image.open("quiz.JPG").convert('L') #open and convert to black and white
pixels = image.load()
width, height = image.size
black_pixels= []
for col in range(width):
for row in range(height):
pixel = pixels[col, row]
if pixel == (0): #select pixels that are black
black_pixels.append((col, row)) #add them to the list of black pixels
def sortCoordinates(lst): #this is just a bubble sort to get the coordinates in order of y values
length = len(lst) -1
solved = False
while not solved:
solved = True
for i in range(length):
if lst[i][1] > lst[i+1][1]:
solved = False
lst[i],lst[i+1] = lst[i+1],lst[i]
return lst
black_pixels = sortCoordinates(black_pixels)
def getShape(black_pixels): # function to generate box from the pixels given
firstPixelXValue = black_pixels[0][0]
lastPixelXValue = black_pixels[-1][0]
tallestPixel = 0
for pixel in black_pixels:
YValue = pixel[1]
if YValue > tallestPixel:
tallestPixel = YValue
topMostPixelYValue = tallestPixel
shortestPixel = pixel[1]
for pixel in black_pixels:
YValue = pixel[1]
if YValue < shortestPixel:
shortestPixel = YValue
bottomMostPixelYValue = shortestPixel
shape = [(firstPixelXValue-4, topMostPixelYValue+2), (lastPixelXValue+4,bottomMostPixelYValue-3)]
return shape
questions = {}
count = 0
count2 = 0
currentQuestionPixels = []
oldPixelY = black_pixels[0][1]
for newPixel in black_pixels:
newPixelY = newPixel[1]
if newPixelY > oldPixelY + 100 or len(black_pixels)-1 == count2: #run this if new question is found
questions[str(count)] = getShape(currentQuestionPixels)
currentQuestionPixels = []
count += 1
oldPixelY = newPixelY
currentQuestionPixels.append(newPixel)
count2 += 1
image = image.convert('RGB')
for question in questions: #draw shape around all questions found
shape = questions.get(question)
img1 = ImageDraw.Draw(image)
img1.rectangle(shape, outline ="red")
image.save("quiz2.JPG")
This should work, in theory, because I am getting all the black pixel coordinates and sorting them out into their Y values. Then I am looping through the black pixels and if the new pixel Y value is grater than the old pixel Y value + 100 or it is the last pixel it must be a new question.
So then I draw a box around all the questions
I've modified the getShape function
Check out the code below
from PIL import Image,ImageDraw
image = Image.open("quiz.JPG").convert('L') #open and convert to black and white
pixels = image.load()
width, height = image.size
black_pixels= []
for col in range(width):
for row in range(height):
pixel = pixels[col, row]
if pixel == (0): #select pixels that are black
black_pixels.append((col, row)) #add them to the list of black pixels
def sortCoordinates(lst): #this is just a bubble sort to get the coordinates in order of y values
length = len(lst) -1
solved = False
while not solved:
solved = True
for i in range(length):
if lst[i][1] > lst[i+1][1]:
solved = False
lst[i],lst[i+1] = lst[i+1],lst[i]
return lst
black_pixels = sortCoordinates(black_pixels)
def getShape(black_pixels): # function to generate box from the pixels given
first_x = 0
first_y = 0
last_x = 99999999
last_y = 99999999
for x, y in black_pixels:
if first_x < x :
first_x = x
if first_y < y :
first_y = y
if last_x > x :
last_x = x
if last_y > y :
last_y = y
shape = [(first_x-4, first_y+2), (last_x+4,last_y-3)]
return shape
questions = {}
count = 0
count2 = 0
currentQuestionPixels = []
oldPixelY = black_pixels[0][1]
for newPixel in black_pixels:
newPixelY = newPixel[1]
if newPixelY > oldPixelY + 100 or len(black_pixels)-1 == count2: #run this if new question is found
questions[str(count)] = getShape(currentQuestionPixels)
currentQuestionPixels = []
count += 1
oldPixelY = newPixelY
currentQuestionPixels.append(newPixel)
# print(currentQuestionPixels)
count2 += 1
image = image.convert('RGB')
for question in questions: #draw shape around all questions found
shape = questions.get(question)
print(shape)
img1 = ImageDraw.Draw(image)
img1.rectangle(shape, outline ="red")
image.save("quiz2.JPG")
i'm having trouble with having my CGI picture and vignette profile image going together to make a vignette picture where the picture is slightly darker around the edges of the picture without compromising the image anywhere else, i am getting everything so far that i think is right but my picture is showing up dark in the middle instead of showing the image normal but with slightly darker colored edges.
this is what i have currently:
def main():
inputPic = makePicture(pickAFile())
vignette = makePicture(pickAFile())
addVignette(inputPic, vignette)
def addVignette(inputPic, vignette):
if getWidth(inputPic) == getWidth(vignette) and getHeight(inputPic) == getHeight(vignette):
explore(inputPic)
explore(vignette)
px1 = getPixels(inputPic)
px2 = getPixels(vignette)
for px in getPixels(inputPic):
x = getX(px)
y = getY(px)
px2 = getPixelAt(vignette, x, y)
x2 = getX(px2)
y2 = getY(px2)
r1 = getRed(px)
r2 = getRed(px2)
g1 = getGreen(px)
g2 = getGreen(px2)
b1 = getBlue(px)
b2 = getBlue(px2)
newR = (r1-r2+104)
newG = (g1-g2+88)
newB = (b1-b2+48)
newC = makeColor(newR, newG, newB)
setColor(px, newC)
explore(inputPic)
folder = pickAFolder()
filename = requestString("enter file name: ")
path = folder+filename+".jpg"
writePictureTo(inputPic, path)
http://i.stack.imgur.com/PqW7K.jpg
picture 1 is what the image needs to be
http://i.stack.imgur.com/PtS4U.jpg
picture 2 is my image i get at the end of my coding
Any help to get me in the right direction would be very much appreciated
After absolutely getting this wrong the first 3 times I worked it out with the help of my little friend the modules operator.
def addVignette(inputPic, vignette):
# Create empty canvas
canvas = makeEmptyPicture(getWidth(inputPic), getHeight(inputPic))
for x in range(0, getWidth(inputPic)):
for y in range(0, getHeight(inputPic)):
px = getPixel(canvas, x, y)
inputPixel = getPixel(inputPic, x, y)
vignettePixel = getPixel(vignette, x, y)
# Make a new color from those values
newColor = getNewColorValues(inputPixel, vignettePixel)
# Assign this new color to the current pixel of the input image
setColor(px, newColor)
explore(canvas)
def getNewColorValues(inputPixel, vignettePixel):
inputRed = getRed(inputPixel)
vignetteRed = getRed(vignettePixel)
inputGreen = getGreen(inputPixel)
vignetteGreen = getGreen(vignettePixel)
inputBlue = getBlue(inputPixel)
vignetteBlue = getBlue(vignettePixel)
newR = inputRed - (255 % vignetteRed) / 3
newG = inputGreen - (255 % vignetteGreen) / 3
newB = inputBlue - (255 % vignetteBlue) / 3
newC = makeColor(newR, newG, newB)
return newC
I'm looking at creating map tiles based on a 3D model made in blender,
The map is 16 x 16 in blender.
I've got 4 different zoom levels and each tile is 100 x 100 pixels. The entire map at the most zoomed out level is 4 x 4 tiles constructing an image of 400 x 400.
The most zoomed in level is 256 x 256 obviously constructing an image of 25600 x 25600
What I need is a script for blender that can create the tiles from the model.
I've never written in python before so I've been trying to adapt a couple of the scripts which are already there.
So far I've come up with a script, but it doesn't work very well. I'm having real difficulties getting the tiles to line up seamlessly. I'm not too concerned about changing the height of the camera as I can always create the same zoomed out tiles at 6400 x 6400 images and split the resulting images into the correct tiles.
Here is what I've got so far...
#!BPY
"""
Name: 'Export Map Tiles'
Blender: '242'
Group: 'Export'
Tip: 'Export to Map'
"""
import Blender
from Blender import Scene,sys
from Blender.Scene import Render
def init():
thumbsize = 200
CameraHeight = 4.4
YStart = -8
YMove = 4
XStart = -8
XMove = 4
ZoomLevel = 1
Path = "/Images/Map/"
Blender.drawmap = [thumbsize,CameraHeight,YStart,YMove,XStart,XMove,ZoomLevel,Path]
def show_prefs():
buttonthumbsize = Blender.Draw.Create(Blender.drawmap[0]);
buttonCameraHeight = Blender.Draw.Create(Blender.drawmap[1])
buttonYStart = Blender.Draw.Create(Blender.drawmap[2])
buttonYMove = Blender.Draw.Create(Blender.drawmap[3])
buttonXStart = Blender.Draw.Create(Blender.drawmap[4])
buttonXMove = Blender.Draw.Create(Blender.drawmap[5])
buttonZoomLevel = Blender.Draw.Create(Blender.drawmap[6])
buttonPath = Blender.Draw.Create(Blender.drawmap[7])
block = []
block.append(("Image Size", buttonthumbsize, 0, 500))
block.append(("Camera Height", buttonCameraHeight, -0, 10))
block.append(("Y Start", buttonYStart, -10, 10))
block.append(("Y Move", buttonYMove, 0, 5))
block.append(("X Start", buttonXStart,-10, 10))
block.append(("X Move", buttonXMove, 0, 5))
block.append(("Zoom Level", buttonZoomLevel, 1, 10))
block.append(("Export Path", buttonPath,0,200,"The Path to save the tiles"))
retval = Blender.Draw.PupBlock("Draw Map: Preferences" , block)
if retval:
Blender.drawmap[0] = buttonthumbsize.val
Blender.drawmap[1] = buttonCameraHeight.val
Blender.drawmap[2] = buttonYStart.val
Blender.drawmap[3] = buttonYMove.val
Blender.drawmap[4] = buttonXStart.val
Blender.drawmap[5] = buttonXMove.val
Blender.drawmap[6] = buttonZoomLevel.val
Blender.drawmap[7] = buttonPath.val
Export()
def Export():
scn = Scene.GetCurrent()
context = scn.getRenderingContext()
def cutStr(str): #cut off path leaving name
c = str.find("\\")
while c != -1:
c = c + 1
str = str[c:]
c = str.find("\\")
str = str[:-6]
return str
#variables from gui:
thumbsize,CameraHeight,YStart,YMove,XStart,XMove,ZoomLevel,Path = Blender.drawmap
XMove = XMove / ZoomLevel
YMove = YMove / ZoomLevel
Camera = Scene.GetCurrent().getCurrentCamera()
Camera.LocZ = CameraHeight / ZoomLevel
YStart = YStart + (YMove / 2)
XStart = XStart + (XMove / 2)
#Point it straight down
Camera.RotX = 0
Camera.RotY = 0
Camera.RotZ = 0
TileCount = 4**ZoomLevel
#Because the first thing we do is move the camera, start it off the map
Camera.LocY = YStart - YMove
for i in range(0,TileCount):
Camera.LocY = Camera.LocY + YMove
Camera.LocX = XStart - XMove
for j in range(0,TileCount):
Camera.LocX = Camera.LocX + XMove
Render.EnableDispWin()
context.extensions = True
context.renderPath = Path
#setting thumbsize
context.imageSizeX(thumbsize)
context.imageSizeY(thumbsize)
#could be put into a gui.
context.imageType = Render.PNG
context.enableOversampling(0)
#render
context.render()
#save image
ZasString = '%s' %(int(ZoomLevel))
XasString = '%s' %(int(j+1))
YasString = '%s' %(int((3-i)+1))
context.saveRenderedImage("Z" + ZasString + "X" + XasString + "Y" + YasString)
#close the windows
Render.CloseRenderWindow()
try:
type(Blender.drawmap)
except:
#print 'initialize extern variables'
init()
show_prefs()
This was relatively simple in the end.
I scaled up the model so that 1 tile on the map was 1 grid in blender.
Set the camera to be orthographic.
Set the scale on the camera to 1 for the highest zoom, 4 for the next one, 16 for the next one and so on.
Updated the start coordinates and move values accordingly.