I try to use SimpleCV example's code(http://www.simplecv.org/), which shows the SimpleCV threshold function, the threshold method sets each pixel in an image to black or white depending on its brightness.
But it doesn't work
Error like this:
ERROR:
Traceback (most recent call last):
File "Camera_1.py", line 37, in <module>
img = Image('http://i.imgur.com/lfAeZ4n.png')
File "c:\Python27\lib\site-packages\SimpleCV\ImageClass.py", line 686, in __in
it__
`source = pil.open(im).convert("RGB")`
NameError: global name 'pil' is not defined
Code like this:
from SimpleCV import Image, Color, Display
# Make a function that does a half and half image.
def halfsies(left,right):
result = left
# crop the right image to be just the right side.
crop = right.crop(right.width/2.0,0,right.width/2.0,right.height)
# now paste the crop on the left image.
result = result.blit(crop,(left.width/2,0))
# return the results.
return result
# Load an image from imgur.
img = Image('http://i.imgur.com/lfAeZ4n.png')
# binarize the image using a threshold of 90
# and invert the results.
output = img.binarize(90).invert()
# create the side by side image.
result = halfsies(img,output)
# show the resulting image.
result.show()
# save the results to a file.
result.save('juniperbinary.png')
Code in here
You need to install the Python Imaging Library (PIL), which is a 3rd party module. I think SimpleCV is supposed to install PIL as part of the overall installation process, but PIL is one of those weirder programs to set up.
Try typing in the following from the command line:
pip install pil
Alternatively, you can install using the binary.
If that still doesn't work, try installing pillow, which is a friendlier and actively-developed fork of PIL:
pip install pillow
Related
I want to make a filter to change the clarity of the image, but no matter what I searched, I could not find any function or algorithm for this.
In your terminal, execute this command: pip install Pillow
from PIL import Image, ImageEnhance
# Read the image
img = Image.open("your-image-path-here.png")
# Image brightness enhancer
enhancer = ImageEnhance.Brightness(img)
factor = 1.3 # Change the value here to change the brightness
img_output = enhancer.enhance(factor)
img_output.save('my-modified-image.png') # You can name "my-modified-image" whatever you want.
I am using Pillow 9.1.0 to flip an image upside-down.
from PIL import Image
img = Image.open('example.png')
flipped = img.transpose(Image.FLIP_TOP_BOTTOM)
Recently a warning shown up:
DeprecationWarning: FLIP_TOP_BOTTOM is deprecated and will be removed in Pillow 10 (2023-07-01). Use Transpose.FLIP_TOP_BOTTOM instead.
flipped = img.transpose(Image.FLIP_TOP_BOTTOM)
I tried to import Transpose from PIL but it did not work.
from PIL import Image, Transpose
Traceback (most recent call last):
File "example.py", line 1, in <module>
from PIL import Image, Transpose
ImportError: cannot import name 'Transpose' from 'PIL' (.../site-packages/PIL/__init__.py)
How to import and use Transpose.FLIP_TOP_BOTTOM properly?
It's all written in the deprecation document. Instead of Image.FLIP_TOP_BOTTOM, you should be using Image.Transpose.FLIP_TOP_BOTTOM.
You forgot save flipped image.
Try to add codeline below.
flipped.save()
So, finally your code must be like that:
from PIL import Image
img = Image.open('example.png')
flipped = img.transpose(Image.FLIP_TOP_BOTTOM)
flipped.save('example.png')
I am trying to detect humans in images using the haarcascade full body algorithm using OpenCv in Python.
when i consider using it on a single image, I face no issues.
import numpy as np
import cv2 as cv
body_cascade = cv.CascadeClassifier(r'...\haarcascade_fullbody.xml')
image = cv.imread(r'...\image.jpg')
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
body = body_cascade.detectMultiScale(gray, 1.01, 4)
for (x,y,w,h) in body:
cv.rectangle(image,(x,y),(x+w,y+h),(255,0,0),3)
But, when I try to use the same program and iterate over several images at once, I get a cryptic OpenCv error. I have some images in a folder and I want to separate images with humans in them from those that don't. I wrote the following:
import os
for file in os.walk(r'...\Folder'):
file=str(file)
im=cv.imread(file)
gray = cv.cvtColor(im, cv.COLOR_BGR2GRAY)
body = body_cascade.detectMultiScale(gray, 1.01, 4)
for (x,y,w,h) in body:
cv.rectangle(im,(x,y),(x+w,y+h),(255,0,0),3)
if(body.size >= 0):
print('okay')
else:
print('Not okay')
But I get the following error :
error: OpenCV(3.4.2) c:\projects\opencv-python\opencv\modules\imgproc\src\color.hpp:253: error: (-215:Assertion failed) VScn::contains(scn) && VDcn::contains(dcn) && VDepth::contains(depth) in function 'cv::CvtHelper<struct cv::Set<3,4,-1>,struct cv::Set<1,-1,-1>,struct cv::Set<0,2,5>,2>::CvtHelper'
for the line gray = cv.cvtColor(im, cv.COLOR_BGR2GRAY)
I am unable to understand what the error is and why the same code that works when taking individual images is working but not the case when iterating through a folder. Do I need to resize the images ?
Also, I tried with keeping just one image in the folder, on which the code had worked before, still doesn't work.
Doc, it seems like OpenCV fails to locate the image. What happens if you're using full paths instead of relative ones? (and what are the three dots there "..." ?)
please dump the file that you read back to disc for debugging purposes and I think you'll be surprised.
I want to paste a bunch of images together with PIL. For some reason, when I run the line blank.paste(img,(i*128,j*128)) I get the following error: ValueError: cannot determine region size; use 4-item box
I tried messing with it and using a tuple with 4 elements like it said (ex. (128,128,128,128)) but it gives me this error: SystemError: new style getargs format but argument is not a tuple
Each image is 128x and has a naming style of "x_y.png" where x and y are from 0 to 39. My code is below.
from PIL import Image
loc = 'top right/'
blank = Image.new("RGB", (6000,6000), "white")
for x in range(40):
for y in reversed(range(40)):
file = str(x)+'_'+str(y)+'.png'
img = open(loc+file)
blank.paste(img,(x*128,y*128))
blank.save('top right.png')
How can I get this to work?
This worked for me, I'm using Odoo v9 and I have pillow 4.0.
I did it steps in my server with ubuntu:
# pip uninstall pillow
# pip install Pillow==3.4.2
# /etc/init.d/odoo restart
You're not loading the image correctly. The built-in function open just opens a new file descriptor. To load an image with PIL, use Image.open instead:
from PIL import Image
im = Image.open("bride.jpg") # open the file and "load" the image in one statement
If you have a reason to use the built-in open, then do something like this:
fin = open("bride.jpg") # open the file
img = Image.open(fin) # "load" the image from the opened file
With PIL, "loading" an image means reading the image header. PIL is lazy, so it doesn't load the actual image data until it needs to.
Also, consider using os.path.join instead of string concatenation.
For me the methods above didn't work.
After checking image.py I found that image.paste(color) needs one more argument like image.paste(color, mask=original). It worked well for me by changing it to this:
image.paste(color, box=(0, 0) + original.size)
I try to find contours in a binary image but when try to execute cvFindContours it gives me that error message
Traceback (most recent call last): File "convert.py", line 30, in
contour = cvFindContours(img2, storage, cv.CV_RETR_CCOMP, cv.CV_CHAIN_APPROX_SIMPLE) File
"/usr/lib/pymodules/python2.7/opencv/cv.py", line 580, in
cvFindContours
count, seq = cvFindContoursUntyped( *args ) File "/usr/lib/pymodules/python2.7/opencv/cv.py", line 6521, in
cvFindContoursUntyped
return _cv.cvFindContoursUntyped(*args) RuntimeError: openCV Error:
Status=Incorrect size of input array
function name=cvStartFindContours
error message=
file_name=/build/buildd/opencv-2.1.0/src/cv/cvcontours.cpp
line=205
I using fresh installed Ubuntu 11.10 and Opencv 2.3.1.
Here is my source code
from opencv.cv import *
from opencv.highgui import *
image = cvLoadImage('test.png')
def getthresholdedimg(image):
size = cvSize(640, 480)
imghsv=cvCreateImage(cvGetSize(image),8,3)
cvCvtColor(image,imghsv,cv.CV_BGR2HSV)
imgblue=cvCreateImage(cvGetSize(image),8,1)
imgblue2=cvCreateImage(cvGetSize(image),8,1)
imgthreshold=cvCreateImage(cvGetSize(image),8,1)
cvInRangeS(imghsv,cvScalar(100,100,100),cvScalar(120,255,255),imgblue)
cvInRangeS(imghsv,cvScalar(100,100,100),cvScalar(120,255,255),imgblue2)
cvAdd(imgblue,imgblue,imgthreshold)
return imgthreshold
cvFlip(image,image,1)
cvSmooth(image, image, CV_GAUSSIAN, 3, 0)
imgthresh=getthresholdedimg(image)
cvErode(imgthresh,imgthresh,None,3)
cvDilate(imgthresh,imgthresh,None,10)
storage = cvCreateMemStorage(0)
img2=cvCloneImage(imgthresh)
contour = cvFindContours(img2, storage, cv.CV_RETR_CCOMP, cv.CV_CHAIN_APPROX_SIMPLE)
my original and binary image
Original image
http://tinypic.com/r/34rul9x/6
and blue filtered binary image
http://tinypic.com/r/ifbotx/6
Find contours in python cv2
import numpy as np
import cv2
img = cv2.imread('sample_image.jpg')
imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,127,255,0)
_, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0,255,0), 3)
cv2.imshow('img',img)
cv2.waitKey(0)
I think this style of API is discontinued from OpenCV. Presently two API is there, old one is cv obtained by
>>> import cv2.cv as cv
And the second and new one is the cv2 available as :
>>> import cv2
Regarding the error :
Replace import statement with from cv2.cv import *
Then remove all the cv prefix, it should work fine.
NOTE :
I think you are trying for color tracking of objects.
But since you have OpenCV 2.3.1, why do you use very old Python API ?
New Python API is cv2 version, which is simple, fast and flexible. Also, it is difficult to play with various objects in Old API compared to new API. So I would recommend you to update to new cv2 API. It is even difficult debug errors in old API.
You can find color tracking code with new cv2 API in this link : http://goo.gl/db2KW
Or if you are sure to use old API, here is the code : http://goo.gl/AFEmv