Converting Image from RGBA to RGB reveals padding, how to crop that?
I'm trying to convert an image from RGBA to RGB. But the conversion to RGB is adding padding to the image. How can I convert without the padding? Or how can I remove it?
img = Image.open('path.png')
img.save("img.png")
rgb_im = img.convert('RGB')
rgb_im.save("rgb_im.png")
Thank you. Images below, before and after conversion:
1 answer
-
answered 2022-05-04 11:41
David
If you open your first image, you'll see that the canvas is larger than the visible image, as you have a transparent frame represented by pixels having
rgba=(255,255,255,0)
. When you remove thealpha
channel by converting RGBA to RGB, that transparency disappear, as onlyrgba=(255,255,255)
remains, which turns out to be the white you see in the second image.So you want to make something similar to what's suggested here
from PIL import Image, ImageChops def trim_and_convert(im): bg = Image.new(im.mode, im.size, (255,255,255,0)) diff = ImageChops.difference(im, bg) diff = ImageChops.add(diff, diff, 2.0, -100) bbox = diff.getbbox() if bbox: return im.crop(bbox).convert('RGB') im = Image.open("path.png") rgb_im = trim_and_convert(im) rgb_im.save("rgb_im.png")
do you know?
how many words do you know
See also questions close to this topic
-
Python File Tagging System does not retrieve nested dictionaries in dictionary
I am building a file tagging system using Python. The idea is simple. Given a directory of files (and files within subdirectories), I want to filter them out using a filter input and tag those files with a word or a phrase.
If I got the following contents in my current directory:
data/ budget.xls world_building_budget.txt a.txt b.exe hello_world.dat world_builder.spec
and I execute the following command in the shell:
py -3 tag_tool.py -filter=world -tag="World-Building Tool"
My output will be:
These files were tagged with "World-Building Tool": data/ world_building_budget.txt hello_world.dat world_builder.spec
My current output isn't exactly like this but basically, I am converting all files and files within subdirectories into a single dictionary like this:
def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree
Right now, my dictionary looks like this:
key:''
.In the following function, I am turning the empty values
''
into empty lists (to hold my tags):def empty_str_to_list(d): for k,v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v)
When I run my entire code, this is my output:
hello_world.dat ['World-Building Tool'] world_builder.spec ['World-Building Tool']
But it does not see
data/world_building_budget.txt
. This is the full dictionary:{'data': {'world_building_budget.txt': []}, 'a.txt': [], 'hello_world.dat': [], 'b.exe': [], 'world_builder.spec': []}
This is my full code:
import os, argparse def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree def empty_str_to_list(d): for k, v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v) parser = argparse.ArgumentParser(description="Just an example", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--filter", action="store", help="keyword to filter files") parser.add_argument("--tag", action="store", help="a tag phrase to attach to a file") parser.add_argument("--get_tagged", action="store", help="retrieve files matching an existing tag") args = parser.parse_args() filter = args.filter tag = args.tag get_tagged = args.get_tagged current_dir = os.getcwd() files_dict = fs_tree_to_dict(current_dir) empty_str_to_list(files_dict) for k, v in files_dict.items(): if filter in k: if v == []: v.append(tag) print(k, v) elif isinstance(v, dict): empty_str_to_list(v) if get_tagged in v: print(k, v)
-
Actaully i am working on a project and in it, it is showing no module name pip_internal plz help me for the same. I am using pycharm(conda interpreter
File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\Scripts\pip.exe\__main__.py", line 4, in <module> File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\site-packages\pip\_internal\__init__.py", line 4, in <module> from pip_internal.utils import _log
I am using pycharm with conda interpreter.
-
Looping the function if the input is not string
I'm new to python (first of all) I have a homework to do a function about checking if an item exists in a dictionary or not.
inventory = {"apple" : 50, "orange" : 50, "pineapple" : 70, "strawberry" : 30} def check_item(): x = input("Enter the fruit's name: ") if not x.isalpha(): print("Error! You need to type the name of the fruit") elif x in inventory: print("Fruit found:", x) print("Inventory available:", inventory[x],"KG") else: print("Fruit not found") check_item()
I want the function to loop again only if the input written is not string. I've tried to type return Under print("Error! You need to type the name of the fruit") but didn't work. Help
-
SwiftUI, apply drawGesture only when over Image
I'm try to apply the gesture only when the user is over the Image display not when tapped outside the image.
Any suggestion how I can do? this following code draw also when user tap outside the image.
struct ContentView: View { @StateObject var am = AppManager() @State var switchToTakePicture = false @State var paths: [PathContainer] = [] @State var currentDraggingId = UUID() @State var spikoPic = #imageLiteral(resourceName: "spiko-16.jpeg") @State var centerOFimage = CGSize(width: 0, height: 0) var body: some View { GeometryReader { proxy in ZStack { Image(uiImage: spikoPic) .resizable() .scaledToFit() .position(x: proxy.size.width/2, y: proxy.size.height/2) .background(GeometryReader { Color.clear.preference(key: ViewRectKey.self, value: [$0.frame(in: .global)]) }) .gesture(drawGesture) // not correct ForEach(paths) { container in // draw and set the foreground color of the paths to red container.path .stroke(Color.red, lineWidth: 4) } } .onPreferenceChange(ViewRectKey.self) { rects in print(rects.first ?? .zero) } } } var drawGesture: some Gesture { DragGesture(minimumDistance: 0) .onChanged { value in // The point that the gesture started from let start = value.startLocation // The point that the gesture ended to let end = value.location // the properties of the rectangle to be drawn let rectangle: CGRect = .init(origin: end, size: .init(width: start.x - end.x, height: start.y - end.y)) // create a path for the rectangle let path: Path = .init { path in path.addRect(rectangle) } print("rettangolo = \(rectangle) orig \(rectangle.origin) - height \(rectangle.height) width = \(rectangle.width)") // remove the previous rectangle that was drawen in current // process of drawing paths.removeAll { $0.id == currentDraggingId } // append the new rectangle paths.append(.init(id: currentDraggingId, path: path)) } .onEnded { _ in // renew the dragging id so the app know that the next // drag gesture is drawing a completely new rectangle, // and is not continuing the drawing of the last rectangle currentDraggingId = .init() } } }
i want no box outside
-
How to clear user uploaded images if the limit of files exceeded in jquery
I have a simple form where a user can upload multiple images. I only want the user to upload 4 images at once, so I did the following:
$("#myfile").on("change", function() { if ($("#myfile")[0].files.length > 4) { alert("You can select only 4 images"); } });
<input type="file" id="myfile" class="form-control" name="pimage[]" multiple="multiple">
This gives an alert when the user uploads more than 4 images but doesn't stop them from submitting the form.
Can anyone please tell me how to clear the user uploaded images if the limit exceeds or disable the submit button?
-
Image Background Remover Using Python
I want to make Image Background Remover Using Python But I do not know how much data It will take and time to reach the accuracy of remove.bg I'm using U-2-Net Ai models https://github.com/xuebinqin/U-2-Net/ Some results are same but not every result is as good enough as remove.bg In a rating I would tell my app as 2/5 and remove.bg as 4/5 Please tell me How can I achieve accuracy like remove.bg Any help or suggestions are appreciated. Thanks
-
Is there a way to guarantee a certain number of lines detected with cv2.HoughLines()?
This question is an extension to my previous question asking about how to detect a pool table's corners. I have found the outline of a pool table, and I have managed to apply the Hough transform on the outline. The result of this Hough transform is below:
Unfortunately, the Hough transform returns multiple lines for a single table edge. I want the Hough transform to return four lines, each corresponding to an edge of the table given any image of a pool table. I don't want to tweak the parameters for the Hough transform method manually (because the outline of the pool table might differ for each image of the pool table). Is there any way to guarantee four lines to be generated by
cv2.HoughLines()?
Thanks in advance.
-
Android app data analysis over supermarket deals images
For an university project i need to create an Android application that collects and aggregates data from various supermarket flyers in order to filter deals by user inserted details.
As inspiration i am looking at commercial applications and i came across Shopfully that have a really interesting feature.
Their app is able to recognize the images of the flyers placing a floating plus button on each product.
Example:
If the user press on the plus floating button product details are showed (price, discount amount):
I am wondering how they made that? I imagine that they use some sort of image recognition to process flyers and an OCR text recognition to parse the text.
Would any of you have any ideas on how I might be able to reproduce this feature?
-
Installing pillow fails on Linux environment or Chrome OS. How do I fix this?
When I try to install pillow with pip3, it gives me the following error message.
failed building wheel for pillow
[omitted text]
Command "/usr/bin/python3 -u -c "import setuptools, tokenize;file='/tmp/pip-install-092vzzoo/pillow/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /tmp/pip-record-v4rw5g1c/install-record.txt --single-version-externally-managed --compile --user --prefix=" failed with error code 1 in /tmp/pip-install-092vzzoo/pillow/
-
PIL ("PIllow") in python 3.10.4 from windows store throws ModuleNotFoundError
In Python 3.10.4, when I try to run any code that has the following line of code in it
from PIL import Image, ImageTk
it returns:
Traceback (most recent call last): File "<stdin>", line 1, in <module> ModuleNotFoundError: No module named 'PIL'
I've tried it on Python 3.9.7 and it worked fine.
-
When I close the Video Chat I recive message that Exception ignored in: <function PhotoImage.__del__ at 0x000002C3C2EB1A60>. Why I get this Error?
I'm trying to build video chat by using cv2 and Tkinter. There is Server And client and with thread they send to each other the frames from their cameras def recv_video(self):
data = b"" payload_size = struct.calcsize("Q") # Q: unsigned long long integer(8 bytes) while self.IsRevcVideo: try: while len(data) < payload_size: packet = self.client_socket_VID.recv(4 * 1024) # 4K, range(1024 byte to 64KB) if not packet: break data += packet # append the data packet got from server into data variable packed_msg_size = data[ :payload_size] # will find the packed message size i.e. 8 byte, we packed on server side. data = data[payload_size:] # Actual frame data msg_size = struct.unpack("Q", packed_msg_size)[0] # message size # print(msg_size) while len(data) < msg_size: data += self.client_socket_VID.recv(4 * 1024) # will receive all frame data from client socket frame_data = data[:msg_size] # recover actual frame data data = data[msg_size:] frame = pickle.loads(frame_data) # de-serialize bytes into actual frame type self.partnerphoto = ImageTk.PhotoImage(image=Image.fromarray(frame)) self.canvasPartnerFrame.create_image(0, 0, image=self.partnerphoto, anchor='nw') self.partner_cnt += 1 print("partnerframe update", self.partner_cnt) except: break
when the server side close the program he call the method with self.window.protocol("WM_DELETE_WINDOW", self.on_closing)
def on_closing(self): print("\nClosing Program") #end loops self.IsRevcVideo = False self.IsUpdateVideo = False self.IsRevcVoice = False self.IsSendVoice = False self.cam.release() self.client_socket_VID.close() self.send_client_socket_VOI.close() self.receive_client_socket_VOI.close() self.window.destroy() print("VIDEO CHAT CLOSED")
and when I click on the X button I get this Error:
Exception ignored in: <function PhotoImage.__del__ at 0x000002C3C2EB1A60> Traceback (most recent call last): File "C:\Users\User\PycharmProjects\LoLevadProject\venv\lib\site-packages\PIL\ImageTk.py", line 145, in __del__ name = self.__photo.name AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
Why the Exception ignored? How to fix it?