简体   繁体   English

无法从opencv中的URL打开图像

[英]Can't open an image from URL in opencv

I'm working on a program that reads csv file to get the names of colors, compares RGB values with RGB values of an image from URL.我正在开发一个程序,该程序读取 csv 文件以获取颜色名称,将 RGB 值与来自 URL 的图像的 RGB 值进行比较。 I think the program doesn't get image from URL since I tried to imshow() to check whether image is passed into program or not.我认为程序没有从 URL 获取图像,因为我尝试使用 imshow() 检查图像是否传递到程序中。 I get this error (-215:Assertion failed) size.width>0 && size.height>0 in function 'imshow'(-215:Assertion failed) size.width>0 && size.height>0 in function 'imshow'

This is the code:这是代码:

import numpy as np #needed to work with matrix of an image
import pandas as pd #needed to work with color.csv
import cv2 #needed to work with image
import matplotlib.pyplot as pl #needed to work with plotting
import urllib.request#needed to work with image url

#step 1. Read csv file with name, RGB and HEX values.
#step 2. Set color detection function. Get value of pixels in a NumPy array
#step 3. Compare RGB value of a pixel with dataframe.
#step 4. Save the name and RBG value inside a file. 

#image from url
def url_to_image(url): #doesn't get file, need to work upon this 
    resp = urllib.request.urlopen(url)
    image = np.asarray(bytearray(resp.read()), dtype='uint8')
    image = cv2.imdecode(image,cv2.IMREAD_COLOR)
    return image

#dataframe with 864 colors 
index = ['color', 'color_name', 'hex','R','G','B'] 
csv = pd.read_csv('colors.csv', names = index, header = None)



def getColor(R,G,B): 
    minimum = 10000
    for i in range(len(csv)):
        distance = abs(R-int(csv.loc[i, 'R'])) + abs(G-int(csv.loc[i, 'G'])) + abs(B-int(csv.loc[i,'B']))
        if(distance<=minimum):
            minimum = distance
            color_name = csv.loc[i, 'color_name']
        return color_name

img = url_to_image("https://upload.wikimedia.org/wikipedia/commons/2/24/Solid_purple.svg")
cv2.imshow("image", img)
cv2.waitKey(0)














It doesn't work because you are trying to use an svg Image (which is vector based) to open in an Matrix like an JPEG or PNG image (which are raster based).它不起作用,因为您正在尝试使用 svg 图像(基于矢量)在矩阵中打开,如 JPEG 或 PNG 图像(基于光栅)。 It doesn't work like that with these.它不适用于这些。

Try loading a different Image like this尝试像这样加载不同的图像

https://miro.medium.com/max/800/1*bNfxs62uJzISTfuPlOzOWQ.png EDIT sry wrong link https://miro.medium.com/max/800/1*bNfxs62uJzISTfuPlOzOWQ.png 编辑错误链接

https://htmlcolorcodes.com/assets/images/colors/purple-color-solid-background-1920x1080.png https://htmlcolorcodes.com/assets/images/colors/purple-color-solid-background-1920x1080.png

this will work because this is an png这会起作用,因为这是一个 png

As far as i know Opencv has no good support for SVG based Images据我所知,Opencv 对基于 SVG 的图像没有很好的支持

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM