I need to flip a picture horizontally, without using the reverse function, I thought I had it right but the error I get is
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
Flip("bm.gif","bm.ppm")
File "C:\Users\....ImageProcessingSKLT.py", line 133, in Flip
pic1 = graphics.getPixel(x,y)
AttributeError: 'module' object has no attribute 'getPixel'
The code I have is
def Flip(image1, image2):
img = graphics.Image(graphics.Point(0, 0), image1)
X = img.getWidth()
Y = img.getHeight()
for y in range(Y//2):
for x in range(X):
pic1 = graphics.getPixel(x,y)
pic2 = graphics.setPixel(X-x,y)
temp = graphics.getColor(pic1)
graphics.setColor(pic1,getColor(pic2))
graphics.setColor(pic2,temp)
image2 = pic2
return image2
What does the error mean? and how do I fix it?
pic1 = graphics.getPixel(x,y)
pic2 = graphics.setPixel(X-x,y)
Probably should be:
pic1 = img.getPixel(x,y)
pic2 = img.setPixel(X-x,y)
The interpreter is complaining that it can't find the getPixel function inside the module graphics; it's img.getPixel, not graphics.getPixel.
Related
I am trying to convert any .png images with a transparent background to a white background.
however I am getting an error that says tuple object is not callable.
I have tried this:
def transparent_to_white(img):
color = (255, 255, 255)
for x in range(img.size()):
for y in range(img.size()):
r, g, b, a = img.getpixel((x, y))
if a == 0:
img.putpixel((x, y), color)
return img
but I get this error:
Original Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/torch/utils/data/_utils/worker.py", line 302, in _worker_loop
data = fetcher.fetch(index)
File "/usr/local/lib/python3.8/dist-packages/torch/utils/data/_utils/fetch.py", line 58, in fetch
data = [self.dataset[idx] for idx in possibly_batched_index]
File "/usr/local/lib/python3.8/dist-packages/torch/utils/data/_utils/fetch.py", line 58, in <listcomp>
data = [self.dataset[idx] for idx in possibly_batched_index]
File "/content/gdrive/My Drive/All_Deep_Learning/PythonCustomLibraries/pix2pixdatasetlib.py", line 49, in __getitem__
y_label = self.resize(transparent_to_white(y_label))
File "/content/gdrive/My Drive/All_Deep_Learning/PythonCustomLibraries/pix2pixdatasetlib.py", line 33, in transparent_to_white
for x in range(img.size()):
TypeError: 'tuple' object is not callable
I am called it in my dataset class :
class Pix2PixDataset(Dataset):
def __init__(self, data_points, transforms = None):
self.data_points = data_points
self.transforms = transforms
self.resize = T.Resize((512,512))
def __getitem__(self, index) :
image, y_label = process_images(self.data_points[index].reference_image, self.data_points[index].drawing )
image = self.resize(image)
y_label = self.resize(transparent_to_white(y_label))
if self.transforms:
image = self.transforms(image)
y_label = self.transforms(y_label)
return(image, y_label)
def __len__(self):
return len(self.data_points)
I tried removing the open and close parenthesis but that did not help, I still get the same error
TypeError: Caught TypeError in DataLoader worker process 0.
Original Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/torch/utils/data/_utils/worker.py", line 302, in _worker_loop
data = fetcher.fetch(index)
File "/usr/local/lib/python3.8/dist-packages/torch/utils/data/_utils/fetch.py", line 58, in fetch
data = [self.dataset[idx] for idx in possibly_batched_index]
File "/usr/local/lib/python3.8/dist-packages/torch/utils/data/_utils/fetch.py", line 58, in <listcomp>
data = [self.dataset[idx] for idx in possibly_batched_index]
File "/content/gdrive/My Drive/All_Deep_Learning/PythonCustomLibraries/pix2pixdatasetlib.py", line 49, in __getitem__
y_label = self.resize(transparent_to_white(y_label))
File "/content/gdrive/My Drive/All_Deep_Learning/PythonCustomLibraries/pix2pixdatasetlib.py", line 33, in transparent_to_white
for x in range(img.size()):
TypeError: 'tuple' object is not callable
Disclaimer: I'm assuming img is an instance of Image class, from module PIL or it's fork Pillow
img.size is a tuple. For example, if you do:
print(img.size)
It prints a tuple with (width, height).
So, your code could be
def transparent_to_white(img):
color = (255, 255, 255)
width, height = img.size # unpacking width/height beforehand
for x in range(width): # using unpacked values in range
for y in range(height)): # same as above
r, g, b, a = img.getpixel((x, y))
if a == 0:
img.putpixel((x, y), color)
return img
Or, alternatively, you could store x and y into a tuple of coordinates, to simplify passing it around:
def transparent_to_white(img):
color = (255, 255, 255)
width, height = img.size # unpacking width/height beforehand
for x in range(width): # using unpacked values in range
for y in range(height)): # same as above
coords = (x, y) # tuple of coordinates
r, g, b, a = img.getpixel(coords) # used here
if a == 0:
img.putpixel(coords, color) # and here
return img
import numpy as np
from PIL import ImageGrab
import cv2
import time
import pyautogui
import matplotlib.pyplot as plt
def make_coords(img,line_param):
slope,intercept=line_param
y1 = img.shape[0]
y2 = int((y1*(3/5)))
x1 = int((y1-intercept)/slope)
x2 = int((y2-intercept)/slope)
try:
return np.array((x1,y1,x2,y2)) #HERE IS WHERE THE PROBLEM HAPPENS
except UnboundLocalError:
pass
def avg_slope(img,lines):
left_fit =[]
right_fit=[]
if lines is not None:
for line in lines:
x1,y1,x2,y2=line.reshape(4)
parameters = np.polyfit((x1,x2),(y1,y2),1)
try:
slope = parameters[0]
except TypeError:
slope = 0
try:
intercept = parameters[1]
except TypeError:
intercept = 0
if slope <0:
left_fit.append((slope,intercept))
else:
right_fit.append((slope,intercept))
if left_fit:
left_fit_avg=np.average(left_fit,axis=0)
left_line=make_coords(img,left_fit_avg)
if right_fit:
right_fit_avg=np.average(right_fit,axis=0)
right_line=make_coords(img,right_fit_avg)
return np.array((x1,y1,x2,y2))
def draw_lines(img, lines):
try:
for line in lines:
if line is not None:
coords = line[0]
cv2.line(img, (coords[0],coords[1]), (coords[2],coords[3]), [255,0,0], 3)
except:
pass
def roi(img):
vertices = np.array([[10,500],[10,300], [300,200], [500,200], [800,300], [800,500]], np.int32)
mask = np.zeros_like(img)
cv2.fillPoly(mask, [vertices], 255)
masked = cv2.bitwise_and(img, mask)
return masked
def process_img(image):
original_image = image
# convert to gray
processed_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# edge detection
processed_img = cv2.GaussianBlur(processed_img,(5,5),0) #new
processed_img = cv2.Canny(processed_img, threshold1 = 50, threshold2=150) #new
# processed_img = cv2.Canny(processed_img, threshold1 = 200, threshold2=300)
lines = cv2.HoughLinesP(processed_img, 1, np.pi/180, 180, np.array([]), minLineLength=15,maxLineGap=5)
avg_lines = avg_slope(processed_img,lines)
draw_lines(process_img,avg_lines)
processed_img = roi(processed_img)
return processed_img
def main():
last_time = time.time()
while True:
screen = np.array(ImageGrab.grab(bbox=(0,40,800,640)))
if screen is not None:
new_screen = process_img(screen)
print('Frame took {} seconds'.format(time.time()-last_time))
cv2.imshow('window', new_screen)
else:
pass
last_time = time.time()
# plt.imshow(new_screen)
#cv2.imshow('window',cv2.cvtColor(screen, cv2.COLOR_BGR2RGB))
# cv2.waitKey(0)
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
main()
THE TERMINAL SHOWS:
avg_lines = avg_slope(processed_img,lines)
Frame took 0.12310576438903809 seconds
Traceback (most recent call last):
File "c:/Users/Nicole/Documents/Python Scripts/matetest.py", line 107, in <module>
main()
File "c:/Users/Nicole/Documents/Python Scripts/matetest.py", line 91, in main 91,
in main
new_screen = process_img(screen) 78, in process_img
File "c:/Users/Nicole/Documents/Python Scripts/matetest.py", line 78, in process_img 50, in avg_slope
avg_lines = avg_slope(processed_img,lines)
File "c:/Users/Nicole/Documents/Python Scripts/matetest.py", line 50, in avg_slope
return np.array((x1,y1,x2,y2))
UnboundLocalError: local variable 'x1' referenced before assignment
... even though I'm doing ...
try:
return np.array((x1,y1,x2,y2))
except UnboundLocalError:
pass
Your Error is actually not occuring where you say it is. By looking at the Traceback you can see that the error is occuring in the function avg_slope.
It might be because you use return np.array((x1,y1,x2,y2)) while in that function you have only declared these values inside an if statement. If the if block would be skipped (when lines is None) then x1, x2, y1and y2 haven't been declared in the function. In other words: it could be that these never exist inside the function, so you can't return something depending on them. The interpreter prevents you from doing this.
You can learn a lot by just reading the error message carefully. Local variable referenced before assignment is in a nutshell what I explained above.
Your problem is here:
def avg_slope(img,lines):
left_fit =[]
right_fit=[]
if lines is not None:
for line in lines:
x1,y1,x2,y2=line.reshape(4)
If lines is "falsey" (empty or None), you never assign to x1.
how to read an image from a function in PIL ? in this scenerio i'm passing a image through paste_image function but it won't support PIL
def paste_image(image):
for i in range(epoches):
im2 = Image.open('/home/navaneeth/work/oneon/1.png')
x, y = im2.size
image.paste(im2, (0, 0, x, y))
image.save("test_"+str(i)+".jpg", "JPEG")
and i'm getting this error
Traceback (most recent call last):
File "main.py", line 109, in <module>
paste_image(image)
File "main.py", line 98, in paste_image
image.paste(im2, (0, 0, x, y))
AttributeError: 'numpy.ndarray' object has no attribute 'paste'
from PIL import Image
im2 = Image.open("/home/navaneeth/work/oneon/1.png")
You can use this code to get the result you want.
I created a code in which, when "load" is clicked, the user will upload a .png image and opencv will perform houghcircle and count the circles.
and the count, will be displayed on the textlabel. The circles.shape would result to (1, 99, 3), and I want to display 99, or even the whole (1, 99, 3) on the textlabel.
the problem is, I get this error after uploading the image
Traceback (most recent call last):
File "try.py", line 58, in Browse
self.label_2.setText(circles.shape)
TypeError: setText(self, str): argument 1 has unexpected type 'tuple'
Here is my code:
def Browse(self):
filter = "Images (*.png)"
fname, _ = QFileDialog.getOpenFileName(self, "Open Image", "Desktop", filter)
print(fname)
self.scene = QGraphicsScene()
self.scene.addPixmap(QPixmap(fname))
self.graphicsView_2.setScene(self.scene)
img = cv2.imread(fname,0)
cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)
circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,5,
param1=200,param2=8,minRadius=0,maxRadius=7)
circles = np.uint16(np.around(circles))
for i in circles[0,:]:
# draw the outer circle
cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),1)
# draw the center of the circle
cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),1)
numberofcells = print(circles.shape)
self.label_2.setText(circles.shape)
any help would be appreciated. Thank you so much!
setText() expects a string but you are passing it a tuple, a possible solution is:
self.label_2.setText(str(circles.shape))
I'm writing a function to convert and display an image to negative, when i call the function i get this error message:
Traceback (most recent call last):
File "C:/Users/User/PycharmProjects/Librophyton/Procdeimagenes/test.py",line 32, in <module>
makeNegative(dude)
File "C:\Python34\lib\ImageProcess.py", line 16, in makeNegative
old = FileImage(imageFile)
File "C:\Python34\lib\cImage.py", line 398, in __init__
super(FileImage, self).__init__(fname = thefile)
File "C:\Python34\lib\cImage.py", line 241, in __init__
self.loadImage(fname)
File "C:\Python34\lib\cImage.py", line 270, in loadTkImage
sufstart = fname.rfind('.')
AttributeError: 'FileImage' object has no attribute 'rfind'
Here is the function:
def makeNegative(imageFile):
window = ImageWin("Proceso de imagen", 1000-100, 900)
old = FileImage(imageFile)
old.draw(window)
window.exitOnClick()
w = old.getWidth()
h = old.getHeight()
new = EmptyImage(w,h)
for row in range(h):
for col in range(w):
pixelviejo = old.getPixel(col,row)
pixelnuevo = pixelNeg(pixelviejo)
new.setPixel(col, row, pixelnuevo)
new.setPosition(w+1, 0)
new.draw(window)
window.exitOnClick()
And here is the funciton call:
dude = FileImage("factores_de_conversion.gif" )
makeNegative(dude)
Any idea how to solve this? or how should i modify the module?