Python image file name

Именовать изображения. python 3.7

Раз руками заполнять, то скачайте все картинки в файл и там руками напишите. Кст, в имя файла нельзя кавычки записать. Если вы хотели в GUI это сделать, то я бы это через pyqt5, странно, что в pygame есть проблемы с юникодом, думаю, вы что-то неправильное делали 🙂

Возможно я не так выразился. У меня есть картинки с надписью «яблоко». Мне нужно записать в json файл «яблоко» (как ключ) и присвоить ему значение списка с изображениями, на которых написано яблоко. Файлы у меня преимущественно пронумерованые. То есть «1.png» .. «250.png».

Нейронку обучаете? 🙂 Т.е. вы сделали программу, что открывает те картинки и вы по содержимому картинки пишите к какому ключу относится и файл той картинки будет добавлен в список json по ключу? Но у вас что-то не получается :/

Нет нет. Вы угадали, но свою задачу я поставил крайне абстрактно. Есть большое изображение список. Эти маленькие изображения — его возможные члены. Их ищем cv2.matchTemplate. Но если на 1 локацию претендуют 2 элемента, то тут обучается нейронка определять один из этих элементов. Так сказать устраняем конфликтные срабатывания. Моя проблема в пальцекровимазохизманестрадании. Эти маленькие изображения должны иметь значения (то есть имена). И их я не могу нормально добавить в json файл ассоциирующий их имя с картинкой. Воот.. pyqt5 вроде подходит. Не уверен. С библиотекой только буду знакомится.

1 ответ 1

  • Установка в консоли: pip install pyqt5
  • Есть папка с картинками: images
  • При запуске через glob загружается список картинок
  • Указывая значения в ключ и нажимая Добавить картинку программа добавит ее в словарь, где ключом будет введенное значение, а значением список файлов картинок
import json import glob from PyQt5.QtWidgets import ( QApplication, QMainWindow, QWidget, QDockWidget, QLabel, QLineEdit, QPushButton, QVBoxLayout, QHBoxLayout, QPlainTextEdit ) from PyQt5.QtGui import QPixmap from PyQt5.QtCore import Qt class MainWindow(QMainWindow): def __init__(self): super().__init__() self._current_index_image = 0 self._images = glob.glob('images/*.png') self._data = dict() self.label_image = QLabel() self.label_image.setFixedSize(400, 400) self.label_image.setScaledContents(True) self.line_edit_key = QLineEdit() self.line_edit_key.setPlaceholderText('Введите ключ картинки. ') self.button_add_file_name = QPushButton('Добавить картинку') self.button_add_file_name.clicked.connect(self._on_add_file_name) self.button_prev = QPushButton('Предыдущая картинка') self.button_prev.clicked.connect(self.load_prev_image) self.button_next = QPushButton('Следующая картинка') self.button_next.clicked.connect(self.load_next_image) layout_control = QHBoxLayout() layout_control.addWidget(QLabel('Ключ:')) layout_control.addWidget(self.line_edit_key) layout_control.addWidget(self.button_add_file_name) layout_control_2 = QHBoxLayout() layout_control_2.addWidget(self.button_prev) layout_control_2.addWidget(self.button_next) self.pl_text_json = QPlainTextEdit() self._dock_widget = QDockWidget('JSON') self._dock_widget.setWidget(self.pl_text_json) self.addDockWidget(Qt.RightDockWidgetArea, self._dock_widget) main_layout = QVBoxLayout() main_layout.addWidget(self.label_image) main_layout.addLayout(layout_control) main_layout.addLayout(layout_control_2) main_layout.addStretch() central_widget = QWidget() central_widget.setLayout(main_layout) self.setCentralWidget(central_widget) self.load_current_image() def get_current_image_file_name(self): return self._images[self._current_index_image] def load_prev_image(self): self._current_index_image -= 1 if self._current_index_image < 0: self._current_index_image = 0 self.load_current_image() def load_next_image(self): self._current_index_image += 1 if self._current_index_image >= len(self._images): self._current_index_image = len(self._images) - 1 self.load_current_image() def load_current_image(self): self.update_states() file_name = self.get_current_image_file_name() pixmap = QPixmap() pixmap.load(file_name) self.label_image.setPixmap(pixmap) def _on_add_file_name(self): key = self.line_edit_key.text() file_name = self.get_current_image_file_name() if key not in self._data: self._dataPython image file name = [] if file_name not in self._dataPython image file name: self._dataPython image file name.append(file_name) self.pl_text_json.setPlainText( json.dumps(self._data, indent=4, ensure_ascii=False) ) def update_states(self): file_name = self.get_current_image_file_name() self.setWindowTitle(f' / : ') if __name__ == '__main__': app = QApplication([]) mw = MainWindow() mw.show() app.exec() 

Источник

Читайте также:  Html view in node js

How to get the file name of image that I put into Dataloader in Pytorch

I have already find the solution yesterday. I’m sorry that I didn’t realize this yesterday. I’m pretty new to Pytorch. You actually could not get file name from DataLoader directly. Here I posted my answer. I hope it could help others.

1 Answer 1

The DataLoader basically can not get the name of the file. But in Dataset , which is the InfDataloader in the question mentioned above, you can get the name of file from the tensor.

class InfDataloader(Dataset): """ Dataloader for Inference. """ def __init__(self, img_folder, target_size=256): self.imgs_folder = img_folder self.img_paths = [] img_path = self.imgs_folder + '/' img_list = os.listdir(img_path) img_list.sort() img_list.sort(key=lambda x: int(x[:-4])) ##文件名按数字排序 img_nums = len(img_list) for i in range(img_nums): img_name = img_path + img_list[i] self.img_paths.append(img_name) # self.img_paths = sorted(glob.glob(self.imgs_folder + '/*')) print(self.img_paths) self.target_size = target_size self.normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) def __getitem__(self, idx): """ __getitem__ for inference :param idx: Index of the image :return: img_np is a numpy RGB-image of shape H x W x C with pixel values in range 0-255. And img_tor is a torch tensor, RGB, C x H x W in shape and normalized. """ img = cv2.imread(self.img_paths[idx]) name = self.img_paths[idx] img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Pad images to target size img_np = pad_resize_image(img, None, self.target_size) img_tor = img_np.astype(np.float32) img_tor = img_tor / 255.0 img_tor = np.transpose(img_tor, axes=(2, 0, 1)) img_tor = torch.from_numpy(img_tor).float() img_tor = self.normalize(img_tor) return img_np, img_tor, name 

Here I add the line name = self.img_paths[idx] and return it.

 with torch.no_grad(): for batch_idx, (img_np, img_tor, name) in enumerate(inf_dataloader, start=1): img_tor = img_tor.to(device) pred_masks, _ = model(img_tor) 

Источник

extracting image file name from the web [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.

Читайте также:  Php see all error

Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn’t work, and the expected results. See also: Stack Overflow question checklist

I am trying to scrape image information from the web and I am wondering if there is any way for me to extract the image file name. For instance if the following HTML expression is stored within the source,

 , 

is it possible that the entry might be simply ? or how about ? if so then src=[«‘]?(. */|/)?(.*(?:png|jpg|gif))(?:\1)?.*>

3 Answers 3

import os >>> path,file_=os.path.split('http://www.adbongo.com/wp-content/uploads/2013/09/digital-bongo.jpg') >>> file_ 'digital-bongo.jpg' 

Note file is a reserved word. file_ or some other variable name should be used instead. I can’t edit because the change is under 6 characters which SO doesn’t allow.

Name the source of the html contents htmlcontent and then use lxml to parse the page:

>>> from lxml import etree >>> html = etree.HTML(htmlcontent) >>> for node in html.xpath('//img/@src'): . print(node.text.rsplit('/', 1)[1]) 

Using BeautifulSoup. This will pull all the links; .jpg, .gif, .png, etc. You can then use further code elaboration to get just jpg or gif or whatever.

import urllib2 from bs4 import BeautifulSoup url1 = "http://www.thrashermagazine.com" content1 = urllib2.urlopen(url1).read() soup = BeautifulSoup(content1) for link in soup.findAll('img'): print link.get('src') ### or alternatively ### for link in soup.findAll('img'): stuff = link.get('src') if '.jpg' in stuff: print stuff #This will only print results with .jpg 

*Just put your url in there. I used that as an example.

Источник

Python split url to find image name and extension

Only downside with this is that your filename will contain a preceding / which you can always remove yourself.

Читайте также:  Month function in javascript

the preceding ‘/’ is not the only problem, if the url contains other subdirectories, they will be kept in the filename, maybe OP wants them, maybe not 😉

@Cédric Julien — Thanks for the reminder about .basename to get just the last portion, edited the post to reflect so. 🙂

This code can work with files without extension and urls like http://server.com/common/image.jpg?xx=345&yy=qwerty BTW in 3.x one need to use from urllib.parse import urlparse

Try with urlparse.urlsplit to split url, and then os.path.splitext to retrieve filename and extension (use os.path.basename to keep only the last filename) :

import urlparse import os.path picture_page = "http://distilleryimage2.instagram.com/da4ca3509a7b11e19e4a12313813ffc0_7.jpg" print os.path.splitext(os.path.basename(urlparse.urlsplit(picture_page).path)) >>> ('da4ca3509a7b11e19e4a12313813ffc0_7', '.jpg') 
filename = picture_page.split('/')[-1].split('.')[0] file_ext = '.'+picture_page.split('.')[-1] 
# Here's your link: picture_page = "http://distilleryimage2.instagram.com/da4ca3509a7b11e19e4a12313813ffc0_7.jpg" #Here's your filename and ext: filename, ext = (picture_page.split('/')[-1].split('.')) 

When you do picture_page.split(‘/’), it will return a list of strings from your url split by a / . If you know python list indexing well, you’d know that -1 will give you the last element or the first element from the end of the list. In your case, it will be the filename: da4ca3509a7b11e19e4a12313813ffc0_7.jpg

Splitting that by delimeter . , you get two values: da4ca3509a7b11e19e4a12313813ffc0_7 and jpg , as expected, because they are separated by a period which you used as a delimeter in your split() call.

Now, since the last split returns two values in the resulting list, you can tuplify it. Hence, basically, the result would be like:

filename,ext = (‘da4ca3509a7b11e19e4a12313813ffc0_7’, ‘jpg’)

Источник

Оцените статью